Thursday, October 20, 2016

ruby on rails: suddenly failing method | Fixed issues

ruby on rails: suddenly failing method | Fixed issues


ruby on rails: suddenly failing method

Posted: 20 Oct 2016 08:23 AM PDT

I am not sure how to present my issue best without posting the whole framework. I have a method duplicate! which should duplicate an object (channel). Usually it works but there is one channel where the method fails and I just don't understand why:

def duplicate!      channel = Channel.new do |c|        c.title = title << ' (copy)'        c.description = description      end      channel.nodes += nodes      playlist.nodes.each { |n| channel.playlist.playlist_items.create(node: n) }      channel    end  

As said nearly all channels duplicate without a problem, but now I have one channel which fails to get duplicated:

2.3.0 :002 > channel.duplicate!  NoMethodError: undefined method `playlist_items' for nil:NilClass      from /var/www/app/models/channel.rb:110:in `block in duplicate!'      from /var/www/app/models/channel.rb:110:in `each'      from /var/www/app/models/channel.rb:110:in `duplicate!'  

Every Channel has Nodes and a Playlist, the error producing Channel has too. I don't really understand the error; how can this method fail depended on the object to duplicate?

Link_to href and text confusion

Posted: 20 Oct 2016 08:23 AM PDT

I have document download functionality for a page. This is the code in place

%td= link_to upload.file, '#', class: " bogus btn btn-xs #{'btn-primary' if upload.published}"  

The problem with this is that results in the following html:

<a href="#" class=" bogus btn btn-xs btn-primary" data-original-title="" title="">/public/uploads/file/46/random.txt</a>  

I thought it would be as simple as changing the structure to this:

%td= link_to '#', upload.file, class: " bogus btn btn-xs #{'btn-primary' if upload.published}"  

which would result in the following html:

<a href="/public/uploads/file/46/random.txt" class=" bogus btn btn-xs btn-primary" data-original-title="" title="">#</a>  

This however results in the following error:

undefined method `model_name' for FileUploader:Class  

Rails errors resets form params

Posted: 20 Oct 2016 08:02 AM PDT

This seems simple, but I can't find anything on it.

I have a link to request a meeting with another user. This produces a url like this:

http://localhost:3000/meetings/new?requestee_id=5  

The requestee id, and other information in the form are passed to the MeetingController:

def create     requestor = current_user   @meeting_with_params = meeting_params   @meeting = Meeting.new(meeting_params)     respond_to do |format|    if @meeting.save      format.html { redirect_to home_url, notice: 'Your lex was successfully requested! Click Plan Meeting ' }      format.json { render :show, status: :created, location: @meeting }    else      format.html { render :new, params: @meeting_with_params }      format.json { render json: @meeting.errors, status: :unprocessable_entity }    end   end  end  

If there are errors, the url now looks like this:

http://localhost:3000/meetings  

which means the form will never submit since the requestee_id is not present.

What is right way to have the user see errors, but the url params are never reset? Thanks!

flash[:error] = '<u>Error in Wells:</u><br />' + flash[:error]

Posted: 20 Oct 2016 08:19 AM PDT

flash[:error] = '<u>Error in Wells:</u><br />' + flash[:error]  

I am getting this error

    AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".): app/controllers/application_controller.rb:70:in `error'    app/controllers/application_controller.rb:441:in `block (2 levels) in parse_job_xml_modern'    app/controllers/application_controller.rb:115:in `each'    app/controllers/application_controller.rb:115:in `block in parse_job_xml_modern'    app/controllers/application_controller.rb:92:in `parse_job_xml_modern'    app/controllers/jobs_controller.rb:1017:in `block in parse_job_xml'    app/controllers/jobs_controller.rb:1012:in `each'    app/controllers/jobs_controller.rb:1012:in `parse_job_xml'    app/controllers/jobs_controller.rb:760:in `parse'        Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.0.  0/lib/action_dispatch/templates/rescues/_source.erb (3.0ms)    Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.0.  0/lib/action_dispatch/templates/rescues/_trace.html.erb (5.0ms)    Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.0.  0/lib/action_dispatch/templates/rescues/_request_and_response.html.erb (2.0ms)    Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.0.  0/lib/action_dispatch/templates/rescues/_web_console.html.erb (1.0ms)    Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.0.  0/lib/action_dispatch/templates/rescues/diagnostics.html.erb within rescues/layo  ut (77.0ms)  

Translating a curl command to httparty

Posted: 20 Oct 2016 07:59 AM PDT

I want to consume some API data from a Rails app. A curl example is curl --data 'api_key=your_api_key&api_secret=your_api_secret&host_id=your_user_host_id' https://api.zoom.us/v1/webinar/list I have experimented with this at the terminal and I am seeing expected responses. I'm now experimenting in a ruby script using httparty. My question is how should I handle the 'stuff' before the endpoint (api_key…secret…ect)? Are these headers?

In regard to curl --data only tells me that it is a post request, but I'm not sure how that translates to httparty.

Here is a first attempt:

require 'httparty'    api_key = 'myKey'  api_secret = 'secret'  host_id = 'host'  data_type = 'JSON'    response = HTTParty.post("api_key&api_secret&host_id&data_type https://api.zoom.us/v1/webinar/list/registration")    puts response.parsed_response  

But this gives me a bad URI response. If I run this same script with the endpoint only I do get a response code back from zoom saying that API key and secret are required.

Rails with dynamic field structure

Posted: 20 Oct 2016 07:39 AM PDT

I am struggling with a Rails system that requires that the user can define their own fields. To illustrate with an example:

Under the model Customer, the user would be allowed to define one or more custom fields like "Age" or "Colour" etc.

My plan has been to implement this by adding two models: CustomFields and CustomFieldsValues and link them like this

Customer -> CustomFieldsValues -> CustomFields

So CustomFieldsValues would have a content, and a customer_id and custom_field_id.

Now since a user can potentially add more CustomFields at any point, I wrote a simple after_initialize function to build any missing relationships.

So lets say that three custom fields exist: "Age", "Colour", "Height". Now whenever a Customer model is initialized it will check if it has these through CustomFieldsValues and build any missing CustomFieldsValues.

I was quite happy with this concept until I started running into a fundamental problem: Whenever a New Customer form fails, Rails will bounce back to the customer form and pre-populate it with the old form data. The problem is that that pre-population seems to happen after the initalization of the Customer object. So it will end up first building all the CustomerFieldsValues and then add whatever was added in the form. So you end up with duplicate fields.

Any suggestions on how to work around this would be greatly appreciated!

Cheers, Charlie

SSL/Namecheap/Heroku Issue Rails

Posted: 20 Oct 2016 07:35 AM PDT

I bought a Positive SSL from NameCheap this morning and tried to set it up. Everything worked fine. Added all the certificates to my heroku app fine and when i tried to connect the new SSL to my Namecheap domain, everything went wrong.

Now my domain is currently re-directing to a random spam website. Spoke to NameCheap customer support and they said it has nothing to do with them that the re-direct is happening on heroku.

I have deleted the certificates and heroku endpoint SSL and my domain is still re-directing to this spam website.

Any help would be appreciated please!!!

Thanks in advance!

What number formatting does a mobile phone can call?

Posted: 20 Oct 2016 07:43 AM PDT

My rails app have a field where users can enter their contact number and I'm using tel: like this to display:

<%= link_to sample.phone, "tel:#{sample.phone}" %>  

So if the user entered a number in the phone field like this: 0176-40206387, the display will also be 0176-40206387

And if the user entered a number in the phone field like this: 017640206387, the display will also be 017640206387

As a newbie, I do not know which format a mobile phone can call, or will the phone automatically converts the number to a callable number? If not, what correct format is callable to tell the user how to enter their phone number?

Getting rails error when using Spaceship::Tunes

Posted: 20 Oct 2016 07:19 AM PDT

In a rails app I am running:

def itunes_all_apps    begin      Spaceship::Tunes.login(params[:itunes_username], params[:itunes_password])      apps = Spaceship::Tunes::Application.all      render json: apps.to_json, status: 200    rescue => e      render json: {error: e, status: 500}.to_json    end  end  

It returns a blank error every time. I have no other feedback to offer in this regard. :/

However, if I change this around slightly, for example getting teams, this works fine:

def itunes_all_apps    begin      spaceship = Spaceship.login(params[:itunes_username], params[:itunes_password])      teams = spaceship.teams      render json: teams.to_json, status: 200    rescue => e      render json: {error: e, status: 500}.to_json    end  end  

I'm not using any fast file or or config or anything. Just passing in a username and password via an api call and trying to get a response back. I'm new to rails so it may be my implementation of the Spaceship examples provided.

Using spaceship 0.32.3 gem

I've poured through the docs to no avail. Grasping for any leads on what I'm doing wrong.

http://www.rubydoc.info/gems/spaceship/Spaceship/Tunes

https://github.com/fastlane/fastlane/blob/master/spaceship/docs/iTunesConnect.md

I really appreciate any suggestions. Thanks.

jQuery: Prevent from outputting a line as text

Posted: 20 Oct 2016 07:11 AM PDT

I am running this js.erb file:

<% if params[:type] == "latest" %>$(".folders").find(".latest").addClass("active -red");<% end %>  

and given that the if statement is true, it does not run this line, instead it just displays it as text in the browser.

What am I doing wrong?

How to get XML doc from downloaded zip file in rails

Posted: 20 Oct 2016 06:42 AM PDT

I have used Typhoeus to stream a zip file to memory, then am iterating through each file to extract the XML doc. To read the XML file I used Nokogiri, but am getting an error, Errno::ENOENT: No such file or directory @ rb_sysopen - my_xml_doc.xml.

I looked up the error and saw that ruby is most likely running the script in the wrong directory. I am a little confused, do I need to save the XML doc to memory first before I can read it as well?

Here is my code to clarify further:

Controller

def index    url = "http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/"    html_response = Typhoeus.get(url)    doc = Nokogiri::HTML(html_response.response_body)      path_array = []    doc.search("a").each do |value|      path_array << value.content if value.content.include?(".zip")    end      path_array.each do |zip_link|      download_file = File.open zip_link, "wb"      request = Typhoeus::Request.new("#{url}#{zip_link}")      binding.pry        request.on_headers do |response|        if response.code != 200          raise "Request failed"        end      end        request.on_body do |chunk|        download_file.write(chunk)      end        request.run        Zip::File.open(download_file) do |zipfile|        zipfile.each do |file|          binding.pry          doc = Nokogiri::XML(File.read(file.name))        end      end    end    end  

file

=> #<Zip::Entry:0x007ff88998373  @comment="",  @comment_length=0,  @compressed_size=49626,  @compression_method=8,  @crc=20393847,  @dirty=false,  @external_file_attributes=0,  @extra={},  @extra_length=0,  @filepath=nil,  @follow_symlinks=false,  @fstype=0,  @ftype=:file,  @gp_flags=2056,  @header_signature=009890,  @internal_file_attributes=0,  @last_mod_date=18769,  @last_mod_time=32626,  @local_header_offset=0,  @local_header_size=nil,  @name="my_xml_doc.xml",  @name_length=36,  @restore_ownership=false,  @restore_permissions=false,  @restore_times=true,  @size=138793,  @time=2016-10-17 15:59:36 -0400,  @unix_gid=nil,  @unix_perms=nil,  @unix_uid=nil,  @version=20,  @version_needed_to_extract=20,  @zipfile="some_zip_file.zip">  

Server-side rendering with react routes in rails

Posted: 20 Oct 2016 06:39 AM PDT

I'm trying to implement server-side react routes in my rails application.

I'm using this gem https://github.com/mariopeixoto/react-router-rails for react-routes and for bundling js files assets pipelines. App is running on local rails server now.

I found only solutions with javascript server in official documentation and almost the same on stackoverflow (with express.js example).

Is there any way how to implement it in rails or Do I have to create new application with the js backend server and somehow interconnect it with my rails app ?

Thanks for the answer.

rails issue with naming convention and table

Posted: 20 Oct 2016 07:47 AM PDT

I have an issue with rails with naming convention.

I have a database where i can't rename table so names are not in plural with inflector.

Today i wanted create model and controller for the table "wishlist__c" and the issue is here. I tried 3 times first by duplicating product model, controller.... and changing name then creating files myself and i still got the issue and then with rails g scaffold wishlist__c

The first error when i try to go to url:8080/wishlist__c/index :

Routing Error uninitialized constant WishlistCController

wishlist__c_controller.rb exist. I notice after many test that the double '__' is a problem in rails. I rename it to wishlist_c_controller and the same with the model. the error message change to

--Solution: I forget to rename folder wishlist__c to wishlist_c in views folder

Thanks you all ! --

ActiveRecord::RecordNotFound in WishlistCController#show Couldn't find WishlistC with 'id'=index

the code display under this is from wishlist_c_controller.rb:

def set_wishlist__c    @wishlist__c = ::WishlistC.find(params[:id])  end  

How to solve it. I need to link my app to this table

edit: Model wishlist_c.rb:

class WishlistC < ApplicationRecord      self.table_name = "wishlist__c"  end  

wishlist_c_controller:

class WishlistCController < ApplicationController    before_action :set_wishlist__c, only: [:show, :edit, :update, :destroy]      # GET /wishlist__c    # GET /wishlist__c.json    def index      @wishlist__c = WishlistC.all    end      # GET /wishlist__c/1    # GET /wishlist__c/1.json    def show    end      # GET /wishlist__c/new    def new      @wishlist__c = WishlistC.new    end      # GET /wishlist__c/1/edit    def edit    end      # POST /wishlist__c    # POST /wishlist__c.json    def create      @wishlist__c = WishlistC.new(wishlist__c_params)        respond_to do |format|        if @wishlist__c.save          format.html { redirect_to @wishlist__c, notice: 'Wishlist  c was successfully created.' }          format.json { render :show, status: :created, location: @wishlist__c }        else          format.html { render :new }          format.json { render json: @wishlist__c.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /wishlist__c/1    # PATCH/PUT /wishlist__c/1.json    def update      respond_to do |format|        if @wishlist__c.update(wishlist__c_params)          format.html { redirect_to @wishlist__c, notice: 'Wishlist  c was successfully updated.' }          format.json { render :show, status: :ok, location: @wishlist__c }        else          format.html { render :edit }          format.json { render json: @wishlist__c.errors, status: :unprocessable_entity }        end      end    end      # DELETE /wishlist__c/1    # DELETE /wishlist__c/1.json    def destroy      @wishlist__c.destroy      respond_to do |format|        format.html { redirect_to wishlist__c_index_url, notice: 'Wishlist  c was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_wishlist__c        @wishlist__c = WishlistC.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def wishlist__c_params        params.fetch(:wishlist__c, {})      end  end  

Error installing nio4r

Posted: 20 Oct 2016 05:36 AM PDT

Help me, please. I'm try to install gem nio4r, but have error with this logs:

ERROR:  Error installing nio4r:      ERROR: Failed to build gem native extension.        current directory: /var/lib/gems/2.3.0/gems/nio4r-1.2.1/ext/nio4r  /usr/bin/ruby2.3 -r ./siteconf20161020-13985-1c6zxok.rb extconf.rb  mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h    extconf failed, exit code 1    Gem files will remain installed in /var/lib/gems/2.3.0/gems/nio4r-1.2.1 for inspection.  Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nio4r-1.2.1/gem_make.out  

I have ubuntu 16.04, ruby 2.3.0, rails 5.0.0.1.

(with some other gems I have similar error (gem bcrypt))

What I must did to fix this bug? Thank's!

bluehost Ruby on Rails Application shared hosting

Posted: 20 Oct 2016 05:37 AM PDT

I'v started working on bluehost (shared hosting) from yesterday and deploying an Rails Application. Available Ruby 1.9.3 and Rails 3.2.13

1) I'm unable to install bundle (it through error rake(11.0) can not load ,bundler can not continue) (How can I install new gems in my project without any error)

2) How can I restart the Rails Server on blue host which is connected on my Subdomain.

Please help!

How do you send Email using Postmark via Rails app?

Posted: 20 Oct 2016 05:17 AM PDT

I've been trying to send this email from my demo rails application using Postmark. I've followed the documentation of their official gem on https://github.com/wildbit/postmark-rails however, from my local system I'm not being able to send emails.

Can anybody here put some light into this topic? Did I miss anything?

how can i Set maximum and minimum length in number_field in RoR

Posted: 20 Oct 2016 05:33 AM PDT

<label class="control-label">count</label>  <%= f.number_field :count, {:placeholder => "Count", :class => "multiple_text_field form-control", :required => true, :max=>"8",:min=>"8" } %>  

Elasticsearch exact match only for specific fields on multi_match fields

Posted: 20 Oct 2016 05:29 AM PDT

Im trying to search only on the following fields:

  1. name (product name)
  2. vendor.username
  3. vendor.name
  4. categories_name

But the results is to wide, I want the results to be exactly what user is typed.

Example:

I type Cloth A I want the result to be exactly Cloth A not something else contain Cloth or A

Here is my attempt:

```

GET /products/_search  {    "query": {      "filtered": {        "query": {          "multi_match": {            "query": "cloth A",             "fields": [              "name",              "vendor.name",              "vendor.username",              "categories_name"            ]           }        },        "filter": [          {            "term": {            "is_available": true            }          },          {            "term": {              "is_ready": true            }          },          {            "missing": {              "field": "deleted_at"            }          }        ]      }    }  }  

```

How do I do that? Thanks in advance

Seahorse::Client::NetworkingError: Connection refused - connect(2) for "localhost" port 8000

Posted: 20 Oct 2016 04:47 AM PDT

I am building a rails application and I use dynamodb (using dynamoid) as the database. For testing, I use dynamodb-local.

When I get into the test database from command line , I get the following error.

Seahorse::Client::NetworkingError: Connection refused - connect(2) for "localhost" port 8000

config/initializers/dynamoid.rb

AWS_CONFIG = YAML.load_file("#{Rails.root}/config/aws.yml")[Rails.env]    Dynamoid.configure do |config|    config.adapter = 'aws_sdk_v2'     config.namespace = AWS_CONFIG['namespace']    config.warn_on_scan = false # Output a warning to the logger when you perform a scan rather than a query on a table.    config.read_capacity = 5 # Read capacity for tables, setting low    config.write_capacity = 5 # Write capacity for your tables  end      if Rails.env.test? || ENV['ASSET_PRECOMPILE'].present?    p "Comes here"    Aws.config[:ssl_verify_peer] = false      Aws.config.update({        credentials: Aws::Credentials.new('xxx','xxx'),        endpoint: 'https://localhost:8000',        region: 'us-west-2'        })  

Rakefile:

 task :start_test_dynamo do    FileUtils.cd('rails-root') do      sh "rake dynamodb:local:test:start"      sh "rake dynamodb:seed"    end   end  

Rails: Get dimensions of image using Carrierwave

Posted: 20 Oct 2016 06:11 AM PDT

I am trying to get the dimensions of an image file that has been uploaded, but has not been saved yet. The problem is I don't understand what the 'file' variable is supposed to be in the ImageUploader's load_dimensions method. Currently file is nil.

This is the code that I am referencing from Carrierwave get image dimensions:

class ImageUploader < CarrierWave::Uploader::Base    include CarrierWave::MiniMagick      process :store_dimensions      private      def store_dimensions      if file && model        model.width, model.height = ::MiniMagick::Image.open(file.file)[:dimensions]      end    end  end  

This is my own code:

image.rb

class Image < ApplicationRecord      belongs_to :author, class_name: 'User', foreign_key: 'user_id'    has_many :request_entries, class_name: 'RequestsHasImage', source: 'requests_has_images'    has_many :requests, through: :request_entries    mount_uploader :filepath, ImageUploader      #Get data of the image file    def load_file_data      if self.filepath        self.width, self.height = self.filepath.load_dimensions()      end      end  

image_uploader.rb

 #Get the dimensions of the image file    def load_dimensions      if file && model          img = ::MiniMagick::Image.open(file.file)        model.width, model.height = img[:dimensions]      end    end  

Concretely, I want to know how to make the file variable in method load_dimensions work with my image model.

Rails 5 Multiple Sums and Join

Posted: 20 Oct 2016 05:15 AM PDT

This question is related to this previously asked question.

My DB columns for model Taxline: ID, RECEIPT, TAXID, BASE, AMOUNT With entries: 1,1,001,30$,3$

2,1,001,50$,5$

3,2,001,20$,2$

And then a second table with columns: TICKETID, TICKETNUMBER

My controller

class TaxlinesController < ApplicationController      def index      @taxlines = Taxline.group(:RECEIPT).sum(:AMOUNT)    end    end  

My view

 <% @taxlines.each do |receipt, amount| %>            <td><%= receipt %></td>          <td><%= amount %></td>   <% end %>  

This works great to show a ticket for each row with corresponding total amount.

Question 1. What is the proper way to also show in view sum of BASE? I tried .sum(:AMOUNT, :BASE) and .sum(:AMOUNT).sum(:BASE) but they both don't work.

Question 2. If now I call in view for instance <%= taxline.TAXID %> I get an error. To solve this I tried to add in view <% @taxlines.each do |receipt, amount, taxid| %> and <td><%= taxid %></td>. And in controller @taxlines = Taxline.group(:RECEIPT).sum(:AMOUNT).select(:TAXID). But it shows a blank column.

Question 3. I want to show TICKETNAME value from TICKETS table.I have already set in Ticketline Model belongs_to :ticket. I assume that after solving question 1 I will be able to do ticketline.ticket.TICKETNAME.Right?

Enums in Rails: uppercase or lowercase?

Posted: 20 Oct 2016 05:27 AM PDT

With most mentions of JAVA enums on the internet, it is everywhere mentioned that enums should be all uppercase (ex: ACTIVE).

Like here: Coding Conventions - Naming Enums

But when it comes to Rails, in all there examples and docs they use lowercase enum value (ex: 'active'), like here: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

which makes sense since rails also provides instance methods by the name of these enums (eg: obj.active?). Is this the only reason why enums in Rails are used as lowercase, or is there more to it? Also we differ from the convention when we use enums as lowercase, should this be the case? or shall we use uppercase enums in Rails as well?

So for example I have a status enum in my model, which can either be active, draft or inactive as per convention, should it be:

enum status: {active: 1, draft: 2, inactive: 3}  

or:

enum status: {ACTIVE: 1, DRAFT: 2, INACTIVE: 3}  

Which one and why?

QT5.7 - Why i get a malformed json value with QString but perfect with std::string?

Posted: 20 Oct 2016 03:51 AM PDT

I try to get a json response from an api in Ruby On Rails.

When I call this url directly with curl or postman I get a perfect json response.

When I use my program with QT5.7 windows compiled in Static for a program in 32bits, I get a perfect response only if use std::string.

But, if I use QDebug for print a QString() I get this malformed and Strange result :

"{\"success\":true,\"files\":[\"C:/Perl/lib/pods/perlcn.pod\",\"C:/Perl/lib/pods/perldata.pod\",\"C:/Perl/lib/pods/perldebguts.pod\",\"C:/Perl/lib/pods/perldelta.pod\",\"C:/Perl/lib/pods/perldiag.pod\",\"C:/Perl/lib/pods/perldoc.pod\",\"C:/Perl/lib/pods/perldos.pod\",\"C:/Perl/lib/pods/perldsc.pod\",\"C:/Perl/lib/pods/perldtrace.pod\",\"C:/Perl/lib/pods/perlebcdic.pod\",\"C:/Perl/lib/pods/perlembed.pod\",\"C:/Perl/lib/pods/perlexperiment.pod\",\"C:/Perl/lib/pods/perlfaq.pod\",\"C:/Perl/lib/pods/perlfaq1.pod\",\"C:/Perl/lib/pods/perlfaq2.pod\",\"C:/Perl/lib/pods/perlfaq3.pod\",\"C:/Perl/lib/pods/perlfaq4.pod\",\"C:/Perl/lib/pods/perlfaq5.pod\",\"C:/Perl/lib/pods/perlfaq6.pod\",\"C:/Perl/lib/pods/perlfaq7.pod\",\"C:/Perl/lib/pods/perlfaq8.pod\",\"C:/Perl/lib/pods/perlfaq9.pod\",\"C:/Perl/lib/pods/perlfilter.pod\",\"C:/Perl/lib/pods/perlfork.pod\",\"C:/Perl/lib/pods/perlform.pod\",\"C:/Perl/lib/pods/perlfreebsd.pod\",\"C:/Perl/lib/pods/perlfunc.pod\",\"C:/Perl/lib/pods/perlgit.pod\",\"C:/Perl/lib/pods/perlglossaƮv

So, if I print std::string, I have a perfect json, exactly what i want :

{"success":true,"files":["C:/Perl/lib/pods/perlcn.pod","C:/Perl/lib/pods/perldata.pod","C:/Perl/lib/pods/perldebguts.pod","C:/Perl/lib/pods/perldelta.pod","C:/Perl/lib/pods/perldiag.pod","C:/Perl/lib/pods/perldoc.pod","C:/Perl/lib/pods/perldos.pod","C:/Perl/lib/pods/perldsc.pod","C:/Perl/lib/pods/perldtrace.pod","C:/Perl/lib/pods/perlebcdic.pod","C:/Perl/lib/pods/perlembed.pod","C:/Perl/lib/pods/perlexperiment.pod","C:/Perl/lib/pods/perlfaq.pod","C:/Perl/lib/pods/perlfaq1.pod","C:/Perl/lib/pods/perlfaq2.pod","C:/Perl/lib/pods/perlfaq3.pod","C:/Perl/lib/pods/perlfaq4.pod","C:/Perl/lib/pods/perlfaq5.pod","C:/Perl/lib/pods/perlfaq6.pod","C:/Perl/lib/pods/perlfaq7.pod","C:/Perl/lib/pods/perlfaq8.pod","C:/Perl/lib/pods/perlfaq9.pod","C:/Perl/lib/pods/perlfilter.pod","C:/Perl/lib/pods/perlfork.pod","C:/Perl/lib/pods/perlform.pod","C:/Perl/lib/pods/perlfreebsd.pod","C:/Perl/lib/pods/perlfunc.pod","C:/Perl/lib/pods/perlgit.pod","C:/Perl/lib/pods/perlglossary.pod","C:/Perl/lib/pods/perlgpl.pod","C:/Perl/lib/pods/perlguts.pod","C:/Perl/lib/pods/perlhack.pod","C:/Perl/lib/pods/perlhacktips.pod","C:/Perl/lib/pods/perlhacktut.pod","C:/Perl/lib/pods/perlhaiku.pod","C:/Perl/lib/pods/perlhist.pod","C:/Perl/lib/pods/perlhpux.pod","C:/Perl/lib/pods/perlhurd.pod","C:/Perl/lib/pods/perlintern.pod","C:/Perl/lib/pods/perlinterp.pod","C:/Perl/lib/pods/perlintro.pod","C:/Perl/lib/pods/perliol.pod","C:/Perl/lib/pods/perlipc.pod","C:/Perl/lib/pods/perlirix.pod","C:/Perl/lib/pods/perljp.pod","C:/Perl/lib/pods/perlko.pod","C:/Perl/lib/pods/perllexwarn.pod","C:/Perl/lib/pods/perllinux.pod","C:/Perl/lib/pods/perllocale.pod","C:/Perl/lib/pods/perllol.pod","C:/Perl/lib/pods/perlmacos.pod","C:/Perl/lib/pods/perlmacosx.pod","C:/Perl/lib/pods/perlmod.pod","C:/Perl/lib/pods/perlmodinstall.pod","C:/Perl/lib/pods/perlmodlib.pod","C:/Perl/lib/pods/perlmodstyle.pod","C:/Perl/lib/pods/perlmroapi.pod","C:/Perl/lib/pods/perlnetware.pod","C:/Perl/lib/pods/perlnewmod.pod","C:/Perl/lib/pods/perlnumber.pod","C:/Perl/lib/pods/perlobj.pod","C:/Perl/lib/pods/perlootut.pod","C:/Perl/lib/pods/perlop.pod","C:/Perl/lib/pods/perlopenbsd.pod","C:/Perl/lib/pods/perlopentut.pod","C:/Perl/lib/pods/perlos2.pod","C:/Perl/lib/pods/perlos390.pod","C:/Perl/lib/pods/perlos400.pod","C:/Perl/lib/pods/perlpacktut.pod","C:/Perl/lib/pods/perlperf.pod","C:/Perl/lib/pods/perlplan9.pod","C:/Perl/lib/pods/perlpod.pod","C:/Perl/lib/pods/perlpodspec.pod","C:/Perl/lib/pods/perlpodstyle.pod","C:/Perl/lib/pods/perlpolicy.pod","C:/Perl/lib/pods/perlport.pod","C:/Perl/lib/pods/perlpragma.pod","C:/Perl/lib/pods/perlqnx.pod","C:/Perl/lib/pods/perlre.pod","C:/Perl/lib/pods/perlreapi.pod","C:/Perl/lib/pods/perlrebackslash.pod","C:/Perl/lib/pods/perlrecharclass.pod","C:/Perl/lib/pods/perlref.pod","C:/Perl/lib/pods/perlreftut.pod","C:/Perl/lib/pods/perlreguts.pod","C:/Perl/lib/pods/perlrepository.pod","C:/Perl/lib/pods/perlrequick.pod","C:/Perl/lib/pods/perlreref.pod","C:/Perl/lib/pods/perlretut.pod","C:/Perl/lib/pods/perlriscos.pod","C:/Perl/lib/pods/perlrun.pod","C:/Perl/lib/pods/perlsec.pod","C:/Perl/lib/pods/perlsolaris.pod","C:/Perl/lib/pods/perlsource.pod","C:/Perl/lib/pods/perlstyle.pod","C:/Perl/lib/pods/perlsub.pod","C:/Perl/lib/pods/perlsymbian.pod","C:/Perl/lib/pods/perlsyn.pod","C:/Perl/lib/pods/perlsynology.pod","C:/Perl/lib/pods/perlthrtut.pod"]}

I have no idea what i can do because i need to parse my json with QString for QJsonDocument and QJsonObject.

I have try many things like QNetworkAccessManager

Or (ugly thing for understand and debug) like : Curl external

Thanks

Rails DRY nested forms for multiple views

Posted: 20 Oct 2016 04:28 AM PDT

I'm trying to create a DRY form that I could use as form_fields for other, nested forms in different view. I'm having 2 problems.

  1. I want the _form partial to not have a submit button, and rather have this button on the form itself. However, clicking the submit button in it's current place doesn't do anything??
  2. The form displays fine in it's current state. If I move the submit button to the _form just to see that it saves, I get a routing error for uninitialized constant UsersController?

My code:

routes.rb

devise_for :users    resources :users do    resources :projects  end  

user.rb model - I'm using Devise.

class User < ApplicationRecord    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable      validates :password, :presence => true,                         :on => :create,                         :format => {:with => /\A.*(?=.{8,})(?=.*\d)(?=.*[\@\#\$\%\^\&\+\=]).*\Z/ }      has_many :projects, inverse_of: :user    accepts_nested_attributes_for :projects    end  

projects.rb model

class Project < ApplicationRecord    belongs_to :user, inverse_of: :projects    ...  end  

projects_controller.rb

class ProjectsController < ApplicationController    ...    def new    @project = current_user.projects.build  end    def create    @project = current_user.projects.new(project_params)    if @project.save      redirect_to root_path, notice: 'Your project is being reviewed. We will be in contact soon!'    else      render :new    end  end    ...    private    ...    def project_params    params.require(:project)          .permit(            :user_id, :project_type_id, :name, :industry_id,             :description, :budget_id, :project_status_id, feature_ids:[], addon_ids:[]          )  end    end  

_form.html.erb partial view

<%= form_for @project do |f| %>          <div class="project_form">      <ol>        <div class="field entry_box">          <li><%= f.label "Give your project a name" %>          <%= f.text_field :name, placeholder: "A short name", class: "form-control entry_field" %></li>        </div>          ...... # All of the other form fields          <div class="field entry_box">          <li><%= f.label "What budget do you have in mind?" %>          <%= collection_select(:project, :budget_id, Budget.all, :id, :list_of_budgets, {include_blank: 'Please select'}, {class: "form-control entry_field"} ) %></li>        </div>      </ol>      # No f.submit button -> moved to view    </div>  <% end %>  

new.html.erb view for new projects

<div class="container">    <div class="center">      <h1>New Project</h1>    </div>      <%= form_for current_user do |f| %>      <%= f.fields_for @project do |builder| %>        <%= render 'form', :locals =>  { f: builder } %>      <% end %>      <div class="actions center space_big">        <%= f.submit "Save Project", class: "btn btn-lg btn-success" %>      </div>    <% end %>  </div>  
  1. How do I get the submit button in it's current position to work?
  2. What's causing the routing error for uninitialized constant UsersController?

jQuery loaded but can't convert object to jQuery

Posted: 20 Oct 2016 03:18 AM PDT

I am using jQuery 1.9.2 and I had no problems with it whatsoever. The problem occurs when I append a string from template(view) to div ( by AJAX request I get data then append).

So I put following lines in the view

var tmp = $(this);   console.log(typeof tmp == jQuery);   if (window.jQuery) { console.log("jQuery is loaded");}  

I always get on tmp type false and when I try its type, it says object. However the next condition is always true. How is it possible that tmp is not a jQuery object?

Start job from another job

Posted: 20 Oct 2016 04:28 AM PDT

Here is what I'm trying to achieve: As a user, I can book a spot for a class. If the class is already full, I'll be on the waiting list. When a new spot is available, I'll receive an email. From then, the app starts a background job that will "wait" 24h. If I haven't confirmed that I'm taking the spot before 24h, it is attributed to the next person on the waiting list, who will also have to confirm before 24h.

The problem is when passing the spot to the next person on the list: since I'm already in the "timer job", I need to call it again with the next person.

class TimerJob    def perform(user_id)      send_confimation_email      if #didn't confirm before 24h        TimerJob.perform(next_user_on_list_id)      else        # save his spot      end     end   end  

The first job works fine, it sends an email, waits for a confirmation within 24h, and then sends another email to the next person on the list but doesn't start another job (line 5). So it won't start the process again if the 24h wait is over.

So the question would be: how can I call a job within a job like in my example ? Is there a reason why this isn't working ?

Or am I over complicating this and a fresh eye would have an easier solution ?

I thought of calling a module from within the job, which would basically call back the job. But same here, didn't work. Any input will be much appreciated.

OpenSSL Seg Fault after upgrading to Sierra - ruby 1.8.7

Posted: 20 Oct 2016 07:09 AM PDT

I've upgraded a working development machine to Sierra and it can no longer deploy using Capistrano.

Tracking it down, the issue is with a call to

OpenSSL::PKey::RSA.new  

This results in

/Users/programmer1/.rvm/rubies/ruby-1.8.7-p374/lib/ruby/1.8/irb.rb:310: [BUG] Segmentation fault  ruby 1.8.7 (2013-06-27 patchlevel 374) [i686-darwin16.0.0]  

I have another Mac which also upgraded to Sierra but it is fine.

I've built ruby, using rvm, against Openssl v0.9.8zg.

rvm reinstall 1.8.7-p374 --autolibs=0 --with-openssl=~/builds/openssl-0.9.8zg  

If I build rvm's ruby against system installed Openssl I can use Capistrano, but Authlogic fails when a user logins into the Ruby on Rails application with a set fault at SSL.

If I build rvm's ruby against OpenSSL v0.9.8zg then Authlogic works correctly, but Capistrano seg faults when connecting to the remote server.

I've tried setting DYLD_LIBRARY_PATH to the locally built OpenSSL v0.9.8 before running Capistrano but it still core dumps.

Ruby on Rails 2.3.18 (legacy Application). Ruby 1.8.7-p374 OS X Sierra

Am out of ideas now how to proceed with this.

Update:

otool -L /Users/programmer1/.rvm/rubies/ruby-1.8.7-p374/lib/ruby/1.8/i686-darwin16.0.0/openssl.bundle    /Users/programmer1/.rvm/rubies/ruby-1.8.7-p374/lib/ruby/1.8/i686-darwin16.0.0/openssl.bundle:  /Users/programmer1/.rvm/rubies/ruby-1.8.7-p374/lib/libruby.dylib (compatibility version 1.8.0, current version 1.8.7)  /opt/local/lib/libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)  /opt/local/lib/libcrypto.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)  /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)  /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)  

shows that ruby is always using libssl1.0.0 and never 0.9.7

How can I tell rvm to link against 0.9.7 of SSL please?

Converting a emai to pdf by binding a erb template that contains instance variable

Posted: 20 Oct 2016 03:09 AM PDT

While sending a mail, I need to convert the mail as a pdf document.

In order to do this i need to bind the erb template with the data, but the erb template contains instance variables

let the template be..,

<h1>Name: <%=@name%><h1>  <h2>Address: <%= @address %><h2>  

I have followed this solution mention in the question, Using a namespace for binding the templates with data.

class Namespace    def initialize(hash)      hash.each do |key, value|        singleton_class.send(:define_method, key) { value }      end     end      def get_binding      binding    end  end    ns = Namespace.new(name: 'Joan', address: 'Chennai, India')  ERB.new(template).result(ns.get_binding)  

This works fine for the templates which doesn't contains instance variables.

I need to pass data to the instance variables in the template is there any possibility for doing this.

And I knew a way to solve this problem by assigning the instance variables with the data that we bind ie)

in the template

   <% @name = name %>      <% @address = address %>     <h1>Name: <%=@name%><h1>     <h2>Address: <%= @address %><h2>  

But I don't want this kind of implementation.

regexp for rails logs

Posted: 20 Oct 2016 03:33 AM PDT

I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.

I need a Regex to find matches for the following:

Here below show the logs for this i need regexp plesase help Thanking you in advance

Started GET \"/\" for 1x2.x6.1xx.2x at 2016-10-20 11:04:00 +0200  Processing by WelcomeController#index as HTML  Current user: anonymous  Redirected to http://example.pro.local/login?back_url=http%xx%xx%2Fexample.pro.local%2F  Filter chain halted as :check_if_login_required rendered or redirected  Completed 302 Found in 3.4ms (ActiveRecord: 1.9ms)"  

Rails many-one relationship for Servers and Disk

Posted: 20 Oct 2016 02:37 AM PDT

I have models Disk and Server. Here more than one Server going to share same Disk. I want to make relationship between Disk and Server. If I use following it becomes meaningless because disk cannot have servers and server have disks.

Class Server < ApplicationRecord    belongs_to :disk  end    Class Disk < ApplicationRecord    has_many :servers  end  

How do I do to make relationship between Server and Disk so that more than one Server share the same disk ?

No comments:

Post a Comment