mardi 4 août 2015

Whats a better way to add conditional input to views in rails?

I have a preview view of a page that I'm building up with a step by step form. Currently the preview view doesn't work, all it has is a default page with default text and styling. My task is to get the preview to display as a user submits the elements of the page through the form. This is what the default view would look like:

<h1>
  Worlds coolest Product
</h1>

<h3>
Buy me and make your life 10x more worthwhile! :)
</h3>

and this default text is rendered out by a partial that looks like this:

<%= render 'manage/deal_steps/deal/main_header' %>

...

My problem is that I need to replace the default text with the user submitted text if there is any but I also need to keep the default text just in case the user doesn't submit any thing. This way I will not get any errors if there is no input. Keeping it simple, Is there any way to achieve this effect without littering the view with conditional logic like this:

<h1>
  <%if retrieve_content('header')!= nil %>
  <%= retrieve_content('header')%>
  <%else%>
  Worlds coolest Product
  <% end%>
</h1>

<h3>
<%if retrieve_content('header_two')!= nil %>
  <%= retrieve_content('header_two')%>
<%else%>
Buy me and make your life 10x more worthwhile! :)
<%end%>
</h3>

How to save nil into serialized attribute in Rails 4.2

I am upgrading an app to Rails 4.2 and am running into an issue where nil values in a field that is serialized as an Array are getting interpreted as an empty array. Is there a way to get Rails 4.2 to differentiate between nil and an empty array for a serialized-as-Array attribute?

Top level problem demonstration:

#[old_app]
 > Rails.version
 => "3.0.3"
 > a = AsrProperty.new; a.save; a.keeps
 => nil

#[new_app]
 > Rails.version
 => "4.2.3"
 > a = AsrProperty.new; a.save; a.keeps
 => []

But it is important for my code to distinguish between nil and [], so this is a problem.

The model:

class AsrProperty < ActiveRecord::Base
  serialize :keeps, Array
  #[...]
end

I think the issue lies with Rails deciding to take a shortcut for attribute that are serialized as a specific type (e.g. Array) by storing the empty instance of that type as nil in the database. This can be seen by looking at the SQL statement executed in each app:

[old_app]: INSERT INTO asr_properties (lock_version, keeps) VALUES (0, NULL)

Note that the above log line has been edited for clarity; there are other serialized attributes that were being written due to old Rails' behavior.

[new_app]: INSERT INTO asr_properties (lock_version) VALUES (0)

There is a workaround: by removing the "Array" declaration on the serialization, Rails is forced to save [] and {} differently:

class AsrProperty < ActiveRecord::Base
  serialize :keeps #NOT ARRAY
  #[...]
end

Allows:

 > a = AsrProperty.new; a.save; a.keeps
 => []

I'll use this workaround for now, but: (1) I feel like declaring a type might allow more efficiency, and also prevents bugs by explicitly prohibiting the wrong data type being stored (2) I'd really like to figure out the "right" way to do it, if Rails does allow it.

So: can Rails 4.2 be told to store [] as its own thing in a serialized-as-Array attribute?

perfect scroll bar is not working for table

I am able to see the scrollbar but unable to scroll the content in the div.

The scroll bar is visible but unable to scroll the content I have attached screenshot of how the scroll bar is rendered.

screenshot.png enter image description here

<div style="height:auto;width:777px;overflow:hidden;margin-left:0px;" id="ios_mdata" class="contentHolder">
    <table class="table table-bordered table-hover table-condensed"  style="margin-left:23px;">
        <thead>
            <tr>
                <th>Version</th>
                <th>App Type</th>
                <th>File Size(MB)</th>
                <th>Release Date</th>
                <th>Minimum OS</th>
                <th>Avg. User Rating</th>
                <th>User Rating Count</th>
                <th>Last Updated</th>
                <th>View in Store</th>
            </tr>
        </thead>
        <tbody>
            <tr>
              <td>5.3</td>
              <td>universal</td>
              <td>12382700.0</td>
              <td>2010-11-05</td>
              <td>7.0</td>
              <td>2</td>
              <td>2</td>
              <td>2015-08-03</td>
              <td>link</td> 
            </tr>
        </tbody>
    </table>
</div>
<style type="text/css">
  .contentHolder { position:relative; margin:0px auto; padding:0px; width: 600px; height: 400px; overflow: scroll; }
  .contentHolder .content { width: 1280px; height: 620px; }
  .table { width: 1200px; }
  .spacer { text-align:center }
  .table-bordered {
    border-collapse: collapse;
  }
</style>
<script type="text/javascript">
    $("#ios_mdata").perfectScrollbar()
</script>

check does memcached store mysql queries

Rails 3.2.18
memcached
dalli

I have added the line to production.rb

  config.cache_store = :dalli_store, '127.0.0.1', {:namespace => 'production'}

And I want that mysql queries will be stored in memcached.
How can I checked that queries are really in memcached.
Dump or something else?
All I found is echo stats | nc 127.0.0.1 11211 I would like to get text of mysql queries stored in memcached.

Thanks in advance.

Display flash message with model validations

I have the following model validations...

  validates :event_id, :uniqueness => {:scope => :email}
  validates_format_of :email, :with => /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/
  validates_presence_of :email, :first_name, :last_name

..and here is my controller...

def register_learner
    @event = Event.find(params[:event_id])
    begin
      EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
    end
end

This codes work, but the problems is it silently catches the errors. I'd like to display a flash message to the user and in the current page. So I tried this...

   def register_learner
    @event = Event.find(params[:event_id])
    begin
      @registation = EventRegistration.create! first_name: params[:first_name], last_name: params[:last_name], email: params[:email], event_id: params[:event_id]
      rescue ActiveRecord::RecordInvalid => e
      if !@registation.valid?
        flash[:notice] = @registation.errors
      end
    end
   end

...but I get the message undefined method `valid?' for nil:NilClass if the validation fails.

Rails Shippo Rates

I am new to using AJAX with rails and would like to display shipping rates via Shippo and AJAX. I am successfully going through the process of creating the rates in the console, but having trouble getting those rates to display so that my users can select their desired shipping rate/price.

Any examples or recommendations?

Push to Git using Rugged

I worked in a script to push to git using a script, so I choose Rugged to do that, my probleme when I try to push to repo, it gives me error, Can you help me ?

require 'rugged'


git_email = 'ettaheri.nizar@gmail.com'
git_name = 'Nizar'
repo_name = '/Users/euphor/Desktop/test/testignore1'


repo = Rugged::Repository.new('/Users/euphor/Desktop/test/testignore1')
puts "1"
index = repo.index
puts "3"

oid = repo.write("This is a blob.", :blob)

index.add(:path => "testignore1", :oid => oid, :mode => 0100644)
puts "4"

options = {}
options[:tree] = index.write_tree(repo)
puts "5"
options[:author] = { :email => git_email, :name => git_name, :time => Time.now }
options[:committer] = { :email => git_email, :name => 'Test Author', :time => Time.now }
puts "6"
options[:message] ||= "Making a commit via Rugged!"
options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
options[:update_ref] = 'HEAD'
puts "7"
Rugged::Commit.create(repo, options)
puts "8"
**repo.push 'origin'**  # this is my error
puts "Done"

the message of my error is :

/Library/Ruby/Gems/2.0.0/gems/rugged-0.23.0/lib/rugged/repository.rb:224:in push': Unsupported URL protocol (Rugged::NetworkError) from /Library/Ruby/Gems/2.0.0/gems/rugged-0.23.0/lib/rugged/repository.rb:224:in push' from vips.rb:43:in `'

You have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4

Similar to problem with rack 1.3.2. You have already activated rack 1.3.2, but your Gemfile requires rack 1.2.3 -- I'm experiencing You have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4 when attempting to run Rails (4.2) in production with Puma and Nginx.

bundle update rake nor rm Gemfile.lock && bundle install seem to help, the only solution I have so far is manually changing rack (1.6.4) to rack (1.6.0) in Gemfile.lock.

Travis CI command is not available from console

I've installed the travis gem

gem install travis

Gem was installed successful, but travis login is not available from console (Ubuntu). Output tells that travis application is not installed and I can install it with sudo apt-get install travis. But it's not that Travis CI I need.

Issue saving images with PaperClip on rails

Hoping you can help with me an issue I'm currently having.

I've set up Paperclip to help me with image uploading and after following instructions and checking various guides, I believe it should be working, but I am running into an issue where it's simply not saving the image and displaying the following error. Can anyone point a learner in the right direction?

I've used imagemagick to convert via the command line without any issues.

UPDATE: I've just looked through my files again and found that I've added this as it asked in the documentation. Do I need to amend the :command_path

UPDATE 2: I have fixed the issue now and my resolution is the answer section belo.

Paperclip.options[:command_path] = "/usr/local/bin/"

.

There was an error processing the thumbnail for f87ef1d19d0a3693810436f1278205e020150803-666-1avrc9e

The extracted source is as follows:

def create
admin = Admin.new(admin_params)

if admin.save
  redirect_to '/administration'

Parameters

{"utf8"=>"✓",
 "authenticity_token"=>"lZ9kDGwvbTUTElcOkKPrgpmiX9HlIfVpAXyRROk/jcRdoGJX9/unlBx6SuazNa9BXw0UIJhbmJiSUVin4DrsBg==",
 "admin"=>{"name"=>"fffsfdsa",
 "email"=>"dfsdfsfadsafsd@gmail.com",
 "user_name"=>"hjdfkhasdjhasjfdkh",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "avatar"=>#<ActionDispatch::Http::UploadedFile:0x007f9082386cf0 @tempfile=#<Tempfile:/var/folders/t6/jrprg2rd57zch5mkt5cg_5cr0000gn/T/RackMultipart20150803-666-1crp2va.jpg>,
 @original_filename="image_name.jpg",
 @content_type="image/jpeg",
 @headers="Content-Disposition: form-data; name=\"admin[avatar]\"; filename=\"image_name.jpg\"\r\nContent-Type: image/jpeg\r\n">},
 "commit"=>"Submit"}

Model (admin.rb)

class Admin < ActiveRecord::Base
has_secure_password

has_attached_file :avatar, :styles => {
    :medium => "300x300>",
    :thumb => "50x50#>"},
    :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end

Admin Controller

 class AdminController < ApplicationController
def new
end

def create
admin = Admin.new(admin_params)

if admin.save
  redirect_to '/administration'
  flash[:success] = "Admin account created successfully"
else
    flash[:error] = "Unable to create account"
  render 'administration/new_ai_admin'
end
end

private

def admin_params
params.require(:admin).permit(:name, :email, :user_name, :password, :password_confirmation, :avatar)
end
end

Rails routes: Wrong singular for resources

I have the following line in my routes.rb (Rails 4.1.4):

resources :request_caches

However, when I run rake routes I get the following output:

request_caches    GET    /request_caches(.:format)            request_caches#index
                  POST   /request_caches(.:format)            request_caches#create
new_request_cach  GET    /request_caches/new(.:format)        request_caches#new
edit_request_cach GET    /request_caches/:id/edit(.:format)   request_caches#edit
request_cach      GET    /request_caches/:id(.:format)        request_caches#show
                  PATCH  /request_caches/:id(.:format)        request_caches#update
                  PUT    /request_caches/:id(.:format)        request_caches#update
                  DELETE /request_caches/:id(.:format)        request_caches#destroy

As you can see, Rails somehow maps request_caches plural to request_cach singular. But it should be request_cache. Is this some kind of special case, because of the word caches? I've also played around with

resources :request_caches, as: :request_cache

But this results in wrong routes like request_cache_index. And furthermore, I think this is a standard task and should be solved clearly using Rails intern route helpers.

So, what am I doing wrong?

Using def_delegate with a hash

I know how Forwardable#def_delegate works with methods on objects, but is there a similar way to forward methods names to hash keys. Like:

hash = { some_value: 42, other_value: 31415 }
def_delegate :hash, :some_value, :other_value

Calling object.some_value should return 42

PS: def and class eval is a way, but is there a nicer way?

how do we encode each byte as two hexadecimal characters in ruby?

I have a hexadecimal number as

hexMidAppId = '0001000000000002'

In node.js, we have a library new Buffer(hexMidAppId, 'hex') which gives me the output as

<Buffer 00 01 00 00 00 00 00 02>

now the same output i want to get it in ruby but i couldn't find any equivalent method in ruby for the Buffer method. Can anyone help me this?

Javascript gem "format.js"

I want to upload file with javascript AJAX but I have an error InvalidAuthenticutyToken when I correct my code like I see on many website another error appear : Unknown format in :

if @personal.save
    format.js
end

In my IDE the .js do an error : cannot find js

I think I miss a gem. My installed gems in order to use javascript are :

gem 'coffee-rails',          '~> 4.1.0'
gem 'coffee-script-source',  '1.8.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder',              '~> 2.0'

And my form is

<%= bootstrap_form_for @personal, :html => {:multipart => true}, :remote => true do |f| %>
<div class="modal-body">
  <%= f.text_field :trigramme, label: "Trigramme" %>
  <%= f.text_field :nom, label: "Nom" %>
  <%= f.text_field :prenom, label: "Prenom" %>
  <%= f.text_field :poste, label: "Poste" %>
  <%= f.text_field :arrivee, label: "Arrivee a OCTO" %>
  <%= f.text_area :bio, label: "Bio", :rows => "5" %>
  <%= f.file_field :img, label: "Photo" %>

</div>
<div class="modal-footer">
  <%= f.submit class: "btn btn-primary" %>
  <%= link_to "Cancel", "#", class: "btn", data: {dismiss: "modal"} %>
</div>

It's weird because when I have the error of Invalid AuthenticutyToken my image is correctly uploaded in database but I have the error. I have some js.erb file that print a popup with the form. I have tried remotipart but nothin happen I have again the error.

Do I miss a gem in order to use javascript due to second error unknownFormat? What is my problem ? Do you have a clue?

In rails, the instance of the model doesn't show up in my table. What is happening when the console says "COMMIT" and "=>true"?

I am pretty new to Ruby on Rails and I'm having some problems. I have already checked out: This stackoverflow question about cloning a model

I am creating a new method for a model that looks like this:

def copy(new_period)
@copy = self.clone
@copy.report_id = Report.maximum(:report_id).next
@copy.period_id = new_period
@copy.save
end

I am trying to create a new instance of report that can be moved to the next year(period). When I run this method in irb I get:

irb(main):003:0> c = r.copy(5)

(1.8ms) SELECT MAX("reports"."report_id") AS max_id FROM "reports"

(0.8ms) BEGIN

(1.0ms) UPDATE "reports" SET "period_id" = 5 WHERE "reports"."report_id" = 438

(1.1ms) COMMIT

=> true

When I look in pgAdmin the new report isn't there. Could someone please explain to me what is going on when the console says "commit" and "=> true"? Does this not mean it has saved to the database?

Rails 3: Displaying conversation list and selected conversation on the same page (using Mailboxer)

Framework: Rails 3/ Jruby with Mailboxer gem.

I want to create a Facebook style inbox page that allows a user to scroll through their Inbox, Sent Items and Trash, whilst keeping the selected conversation displayed on the right hand side of the page (like Facebook's implementation of the desktop inbox)

The action of clicking the conversation title should render that entire conversation to the right side of the page, avoiding the need of dedicating an entire page to one conversation within the web browser. This is so (in a later version) I can implement an AJAX call that will only refresh the conversation part of the page, whilst allowing the user to keep an eye on their conversation list.

My problem is, I'm completely stumped as to how this would be implemented, without the routing error No route matches [GET] "/conversations/20/show_conversation" that I'm currently getting. I'm fairly new to Ruby on Rails, so the whole routing side of things is a bit confusing.

My question how do I display all my conversations, as well as the transcript of one selected conversation (at any given time) on the same page. Preferably, I would like to avoid the use of Javascript/ jQuery and stick to the Ruby on Rails implementation, if possible.

Here's a screenshot of my "messages" page, where "Conversation.." (on the right) should display the transcript of the conversation I had with the target user.

enter image description here

My controller code for the current page:

class ConversationsController < ApplicationController
    before_filter :authenticate_user!
    before_filter :get_mailbox
    before_filter :get_conversation, except: [:index]
    before_filter :get_box, only: [:index]
    before_filter :get_conversation, except: [:index, :empty_trash]

    def index
        @conversations = @mailbox.inbox.paginate(page: params[:page], per_page: 10)
        @inbox = @mailbox.inbox.paginate(page: params[:page], per_page: 10)
        @trash = @mailbox.trash.paginate(page: params[:page], per_page: 10)
        @sent = @mailbox.sentbox.paginate(page: params[:page], per_page: 10)
    end

    def show_conversation
        @conversation
        redirect_to conversations_path
    end 

    [...]

    private 

    def get_mailbox
        @mailbox ||= current_user.mailbox
    end

    def get_conversation 
        @conversation ||= @mailbox.conversations.find(params[:id])
    end

    def get_box
        if params[:box].blank? or !["inbox","sent","trash"].include?(params[:box])
            params[:box] = 'inbox'
        end
        @box = params[:box]
    end
end

My corresponding views: index.html.erb

<% page_header "Your Conversations" %>

<p><%= link_to 'Start conversation', new_message_path, class: 'btn btn-lg btn-primary' %> 
<%= link_to 'Empty trash', empty_trash_conversations_path, class: 'btn btn-danger', 
    method: :delete, data: {confirm: 'Are you sure?'} %></p>

<!-- tab things, they're awesome -->
<div class="left_col">
  <div class="col-sm-3">
    <ul class="nav nav-pills">
      <%= mailbox_section 'inbox', @box %>
      <%= mailbox_section 'sent', @box %>
      <%= mailbox_section 'trash', @box %>
    </ul>
  </div>

  <!-- this working part isn't in the tutorial -->
  <% if @box == 'trash' %>
    <%= render partial: 'conversations/conversation', collection: @trash %>
  <% elsif @box == 'inbox' %>
    <%= render partial: 'conversations/conversation', collection: @inbox %>
  <% elsif @box == 'sent' %>
   <%= render partial: 'conversations/conversation', collection: @sent %>
  <% end %>   
  <%= will_paginate %>
</div>

<div class="right_col"> 
  <p><small>Conversation...</small></p>
  <%= @conversation %> <!-- should I have a partial or something? -->
</div>

_conversation.html.erb partial where the link to show_conversation is

<%= link_to conversation.subject,   show_conversation_conversation_path(conversation) %>

<div class="btn-group-vertical pull-right">
    <% if conversation.is_trashed?(current_user) %>
        <%= link_to 'Restore', restore_conversation_path(conversation),
                         class: 'btn btn-xs btn-info', method: :post %>
    <% else %>
        <%= link_to 'Move to trash', conversation_path(conversation), 
                         class: 'btn btn-xs btn-danger', method: :delete,
                  data: {confirm: 'Are you sure?'} %>

        <% if conversation.is_unread?(current_user) %>
            <%= link_to 'Mark as read', mark_as_read_conversation_path(conversation), 
                    class: 'btn btn-xs btn-info', method: :post %>
        <% end %>
    <% end %>
</div>

<p><%= render 'conversations/participants', conversation: conversation %></p>

<p><%= conversation.last_message.body %>
  <small>(<span class="text-muted">
<%= conversation.last_message.created_at.strftime("%-d %B %Y, %H:%M:%S") %>
</span>)</small></p>

And finally, my routes.rb

resources :conversations, only: [:index, :show, :destroy] do
    member do
        post :reply, :restore, :mark_as_read, :show_conversation
    end

    collection do 
        delete :empty_trash
    end
end

resources :messages, only: [:new, :create]

root :to => 'conversations#index'

I do have a working conversation partial that builds the conversation on a separate page. It works fine, but I haven't included it because I want to move away from having a separate page to view the conversation. Any help on this would be greatly appreciated!

Thanks,

How can I get zbar to deploy on Heroku?

I am using the ruby-zbar gem in a rails app to scan barcodes from jpgs. I installed the zbar library using homebrew on my local machine and everything works fine. However, when deploying to Heroku I consistently get errors such as the following:

remote:        LoadError: Didn't find libzbar on your system
remote:        Please install zbar (http://ift.tt/refsyg) or set ZBAR_LIB if it's in a weird place
remote:        FFI::Library::ffi_lib() failed with error: library names list must not be empty

I've tried following the advice from this Stack Overflow post (Heroku Zbar Didn't find libzbar on your system (LoadError)), namely to set the ZBAR_LIB ENV variable to /app/vendor/lib/libzbar.so, or failing that to run heroku bash and try to find a file named libzbar.so and point ZBAR_LIB to its path.

However, I can't seem to find the heroku buildpack referenced in the original Stack Overflow post (the link to http://ift.tt/1mpaR2J goes to a 404 page), so I can't replicate the solution outlined there.

I have tried all of the following buildpacks:

http://ift.tt/1ImOq5Q
http://ift.tt/1KO1BT3
http://ift.tt/1ImOsdY

During the build process I can see hopeful messages like this:

remote: -----> Multipack app detected
remote: -----> Fetching custom git buildpack... done
remote: -----> ZBAR app detected
remote: -----> Downloading and installing ZBAR
remote: -----> Configuring ZBAR
remote: -----> Make!
remote: -----> Make install !!!
remote: -----> Writing profile script
remote: -----> Fetching custom git buildpack... done
remote: -----> Ruby app detected
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.2.1

But setting ZBAR_LIB to /app/vendor/lib/libzbar.so gives me some version of this error:

remote:        LoadError: Didn't find libzbar on your system
remote:        Please install zbar (http://ift.tt/refsyg) or set ZBAR_LIB if it's in a weird place
remote:        FFI::Library::ffi_lib() failed with error: Could not open library '/app/vendor/lib/libzbar.so': /app/vendor/lib/libzbar.so: cannot open shared object file: No such file or directory

And trying to find libzbar.so on heroku run bash has not been successful for me -- I can see many files that are similar in name (even a libzbar.rc) but none that fits the bill.

~ $ find / -name '*libzbar*'
find: `/var/lib/polkit-1': Permission denied
/app/vendor/zbar/plugin/.deps/plugin_libzbarplugin_la-plugin.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-QZBar.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-QZBarThread.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-moc_QZBarThread.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-moc_QZBar.Plo
/app/vendor/zbar/gtk/.deps/gtk_libzbargtk_la-zbargtk.Plo
/app/vendor/zbar/gtk/.deps/gtk_libzbargtk_la-zbarmarshal.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-symbol.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-video.o
/app/vendor/zbar/zbar/zbar_libzbar_la-error.lo
/app/vendor/zbar/zbar/processor/zbar_libzbar_la-lock.lo
/app/vendor/zbar/zbar/processor/.libs/zbar_libzbar_la-lock.o
/app/vendor/zbar/zbar/processor/zbar_libzbar_la-lock.o
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-x.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-posix.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-lock.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-win.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-config.o
/app/vendor/zbar/zbar/zbar_libzbar_la-processor.o
/app/vendor/zbar/zbar/zbar_libzbar_la-refcnt.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-convert.o
/app/vendor/zbar/zbar/zbar_libzbar_la-video.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-window.o
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-v4l1.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-v4l2.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-vfw.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-processor.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-image.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-refcnt.o
/app/vendor/zbar/zbar/zbar_libzbar_la-error.o
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-qrdectxt.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-binarize.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-isaac.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-rs.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-qrdec.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-bch15_5.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-util.Plo
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-video.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-config.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-processor.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-convert.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-window.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-refcnt.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-error.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-img_scanner.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-image.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-symbol.o
/app/vendor/zbar/zbar/zbar_libzbar_la-img_scanner.o
/app/vendor/zbar/zbar/zbar_libzbar_la-image.o
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-dib.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-xv.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-x.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-ximage.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-win.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-img_scanner.lo
/app/vendor/zbar/zbar/libzbar.rc
/app/vendor/zbar/zbar/zbar_libzbar_la-symbol.o
/app/vendor/zbar/zbar/zbar_libzbar_la-config.lo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-decoder.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-config.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-convert.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-processor.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-symbol.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-scanner.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-error.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-jpeg.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-video.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-window.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-refcnt.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-svg.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-img_scanner.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-image.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-window.lo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-code39.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-pdf417.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-qr_finder.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-i25.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-ean.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-code128.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-convert.lo

Has anyone had success getting zbar to run on heroku? If so, what buildpack did you use? I would be thrilled to learn how to make this work.

Elasticsearch stops after import data from model

  1. I deployed my app to vps.
  2. Started Elasticsearch, and checked it with ps aux | grep elasticsearch
  3. cd app/currect && RAILS_ENV=production bin/rails c
  4. User.import

    Output:

    Scoped order and limit are ignored, it's forced to be batch order and batch size  
      User Load (0.4ms)  SELECT "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 10
    Faraday::ConnectionFailed: connection refused: localhost:9200
    
    
  5. Elasticsearch stopped and import doesn't work, why ?

I am using Ubuntu 14, Puma server, SQLite database. Does it matter?

Additional notes:

http://ift.tt/1P3OOuv - gemfile.lock from project

http://ift.tt/1IVORti - elasticsearch config

http://ift.tt/1P3OOux - elasticsearch log

Before User.import

ps aux | grep elasticsearch

shows elasticsearch process

After User.import ps aux | grep elasticsearch doesn't show process

How to check if elasticsearch uses 9200 port ?

Ruby- web api with rest client gem

I'm new in Ruby (and in developing too) and I would like to get the response from another url (my url) in the get method.

i'm using rest-client gem.

I have tried this code:

class UsersController < ApplicationController require 'rest-client' def index

RestClient::Request.execute( method: :get, url: 'https://my-url')

end

end

but when I open http://localhost:3000/users I get a blank page

Thanks in advance,

Joel

onclick passing data to javascript

I have a link that when clicked should assign a rails variable to a javascript variable. The javascript is then used to calculate the price. i have price calculated with it hard coded in the javascript.

in the html i need "data-price" to be "var blankPrice" in the js. Any help would be great.

function calculatePrice(){

                var blankPrice = 5;


                console.log(blankPrice)
                var pricePerSide = 3;

                var printedSides = 0;

                if (frontCanvas) {
                        var frontCanvasJson = JSON.parse(frontCanvas);
                        
                        if (frontCanvasJson && frontCanvasJson.objects.length > 0)
                                printedSides++;
                }

                if (backCanvas) {
                        var backCanvasJson = JSON.parse(backCanvas);

                        if (backCanvasJson && backCanvasJson.objects.length > 0)
                                printedSides++;
                }

                var total = blankPrice + (pricePerSide * printedSides);
                $('.base-price').text('$' + total);
         }

         function saveCampaign() {
                campaign.front_canvas = frontCanvas;

                $.post('/campaigns', campaign);
         }
<a 
   tabindex="-1" 
   data-original-title="<%= shirt_color.color_name.titleize %>"
   class="shirt-color-link" 
   data-color="#<%= shirt_color.hex %>" 
   data-price="<%= product.base_price %>" 
   data-product-id="<%= product.id %>">
   <table>
     <tr>
                <td style="border: 1px solid #DDD" bgcolor="#<%= shirt_color.hex %>"></td>
                <td style="padding-left: 10px;"><%= shirt_color.color_name.titleize %></td>
        </tr>
   </table>
</a>

How to get a hover effect for glyphicon icons?

I'm trying to make glyphicon icon appear every time I hover my mouse over it. And I'm using <span> tag for it. But this refuses to work. What have I done wrong?

application.scss

 /*
 *= require bootstrap3-editable/bootstrap-editable
 *= require bootstrap-datepicker3
 *= require_tree .
 */

  @import "bootstrap-sprockets";
  @import "bootstrap";

.hovering:before {
display: none;
}

.hovering:hover:before {
display: block;
}

In my view file it looks like this:

  <span class='hovering'>
    <%= link_to user_task_path(current_user, task.id), method: :delete,
    data: { confirm: 'Are you sure?' }, remote: true do %>
      <i class="glyphicon glyphicon-trash"></i>
    <% end %>
  </span>

rails has_secure_password. is it possible to change user's password in DB

I have rails project with user's authorization with has_secure_password. So, password store in DB as encrypted password.

Now I want to add following: User will be able to change his current password to new password and this new password must be encrypted in DB too.

I can not find any information about it.

Is there way to do it with has_secure_password?

Adding a field to searchable fails to include the field in solr

ruby 2.1.5
rails 3.2.3

In my gemfile, I have:

gem 'sunspot_rails'
gem 'sunspot_solr'

In my tickets_controller.rb, I have the following:

def index
  params[:direction] ||= "desc"
  params[:sort] ||= "requested_date_start"
  @tickets = Ticket.solr_search( include: [:customer_info, :customer, :executor, :notes] ){
    fulltext params[:query] if params[:query].present?
    with :status, (params[:status] || params[:filter]) if (params[:status] || params[:filter]).present?
    order_by( params[:sort], params[:direction] ) if params[:sort].present? && params[:direction].present?
    paginate :page => params[:page], per_page: params[:per_page]
  }.results
  render partial: 'tickets' if request.xhr?
end 

In my ticket.rb, I have:

searchable do
  time(:deleted_at)
  text :services do services.map(&:name) end
  text :inventories do inventories.map(&:name) end
  text :requested_date_start
  text :number
  text :customer_phone do customer_info.try(&:phone) end
  text :sp_name do executor.try(&:full_name) end
  text :specialties do specialties.map(&:top_code) end
  double :number
  string :customer_id
  string :executor_id
  string :id
  string :technician_ids, multiple: true
  string :customer_location_id, using: :location_id
  string :customer_name do customer_info.try(&:full_name) end
  string :customer_phone do customer_info.try(&:phone) end
  string :executor_location_id do executor_location.try(&:id) end
  string :originator_name do customer.try(&:full_name) end
  string :sp_name do executor.try(&:full_name) end
  REPORTCOLUMNS.except!(:customer_info_full_address).each do |k, v|
    case v[:type]
    when 'string'
      text(k){instance_eval(v[:path]) rescue nil}
      string(k){instance_eval(v[:path]).downcase rescue nil}
    when 'datetime'
      time(k){instance_eval(v[:path]) rescue nil}
    when 'double'
      double(k){instance_eval(v[:path]) rescue nil}
    end
  end
end

Search is working fine. I wanted to include customer_reference, which is a column in the tickets tables in the search, so I added it to searchable in ticket.rb, as follows:

searchable do
  time(:deleted_at)
  text :services do services.map(&:name) end
  text :inventories do inventories.map(&:name) end
  string :customer_reference
  text :requested_date_start
  text :number
  text :customer_phone do customer_info.try(&:phone) end
  text :sp_name do executor.try(&:full_name) end
  text :specialties do specialties.map(&:top_code) end
  double :number
  string :customer_id
  string :executor_id
  string :id
  string :technician_ids, multiple: true
  string :customer_location_id, using: :location_id
  string :customer_name do customer_info.try(&:full_name) end
  string :customer_phone do customer_info.try(&:phone) end
  string :executor_location_id do executor_location.try(&:id) end
  string :originator_name do customer.try(&:full_name) end
  string :sp_name do executor.try(&:full_name) end
  REPORTCOLUMNS.except!(:customer_info_full_address).each do |k, v|
    case v[:type]
    when 'string'
      text(k){instance_eval(v[:path]) rescue nil}
      string(k){instance_eval(v[:path]).downcase rescue nil}
    when 'datetime'
      time(k){instance_eval(v[:path]) rescue nil}
    when 'double'
      double(k){instance_eval(v[:path]) rescue nil}
    end
  end
end

I uploaded the new ticket.rb to the staging server and did the following:

bundle install
bundle exec rake RAILS_ENV=staging  db:migrate
chmod -R -- g+w /home/app
RAILS_ENV=staging RAILS_GROUPS=assets bundle exec rake assets:precompile
sudo reboot
echo \"DEPLOY SIDEKIQ RELOAD $(date)\" >> log/sidekiq.log
bundle exec sidekiq -d -L log/sidekiq.log -e staging
RAILS_ENV=staging bundle exec rake sunspot:solr:start
screen -d -m sh -c 'cd /home/app && RAILS_ENV=staging bundle exec rake sunspot:solr:reindex'

When I did a search with a customer_reference, it did not find it. When I looked at the solr log file, I found the following:

INFO: [development] webapp=/solr path=/select params={fl=*+score&sort=requested_date_start_d+desc&start=0&q=139170&qf=services_text+inventories_text+requested_date_start_text+number_text+customer_phone_text+sp_name_text+specialties_text+status_text+ticket_type_text+executor_full_name_text+customer_full_name_text+customer_info_full_name_text+ticket_profile_name_text&wt=ruby&fq=type:Ticket&rows=20&defType=edismax} hits=1 status=0 QTime=27 

customer_reference is not there. This is the first time I use solr, and I am trying to maintain this code. Any ideas what I'm doing wrong?

Rails "destroy" method doesn't work after where quoery

Hello I have this function in my controller

  def destroy
    fallower = Fallower.where(user_id: 1, author_id: 2).first
    fallower.destroy

    respond_to do |format|
      format.js
    end
  end

it throws me this error

ActiveRecord::StatementInvalid in FallowersController#destroy

PG::SyntaxError: ERROR:  zero-length delimited identifier at or near """"
LINE 1: DELETE FROM "fallowers" WHERE "fallowers"."" = $

any idea why normal destroy function doens't work this time?

vanity gem don't track conversions

[EDIT]: added a github issue

some infos about versions:

ruby 2.2.2 rails 4.1.12 vanity (2.0.0.beta8) - from master branch on github

I followed the guide at http://ift.tt/Sin99n . I did all the steps, I'm using activerecord adapter to connect to the db. I implemented the following example in the guide:

Step 2: Define your first A/B test

This experiment goes in the file experiments/price_options.rb:

ab_test "Price options" do
  description "Mirror, mirror on the wall, who's the better price of all?"
  alternatives 19, 25, 29
  metrics :signups
end
If the experiment uses a metric as above (“signups”), there needs to be a corresponding ruby file for that metric, experiments/metrics/signups.rb.

metric "Signup (Activation)" do
  description "Measures how many people signed up for our awesome service."
end
Step 3: Present the different options to your users

<h2>Get started for only $<%= ab_test :price_options %> a month!</h2>
Step 4: Measure conversion

Conversions are created via the track! method. For example:

class SignupController < ApplicationController
  def signup
    @account = Account.new(params[:account])
    if @account.save
      track! :signups
      redirect_to @acccount
    else
      render action: :offer
    end
  end
end

The tracking of the metrics seems to work, while the 'conversion' field on vanity dashboard remains fixed at 0

no clue how to fix.

Thanks in advance

Rails Puma running out of Redis connections

I've looked around at other similar questions on SO but can't quite piece things together well enough. I have a Rails app (on Heroku) that uses Puma with both multiple processes and multiple threads. My app also uses Redis as a secondary data store (in addition to a SQL database), querying Redis directly (well, through the connection_pool gem). Here's my Puma config file:

workers Integer(ENV["WEB_CONCURRENCY"] || 4)
threads_count = Integer(ENV["MAX_THREADS"] || 5)
threads threads_count, threads_count

preload_app!

rackup DefaultRackup
port ENV["PORT"] || 3000
environment ENV["RACK_ENV"] || "development"

on_worker_boot do
  # Worker specific setup for Rails 4.1+
  ActiveRecord::Base.establish_connection

  redis_connections_per_process = Integer(ENV["REDIS_CONNS_PER_PROCESS"] || 5)
  $redis = ConnectionPool.new(size: redis_connections_per_process) do
    Redis.new(url: ENV["REDIS_URL"] || "redis://localhost:6379/0")
  end
end

My Redis instance has a connection limit of 20, and I find myself regularly going over this limit, despite having what should be (as far as I can tell) only 5 connections per process spread across 4 worker processes.

In fact, I even get max number of clients reached Redis errors when I set REDIS_CONNS_PER_PROCESS to 1. Is on_worker_boot called for each thread rather than each process?

I've also tried having a separate redis.rb initializer, which works but only when REDIS_CONNS_PER_PROCESS is 1, which seems odd since I should be able to have it up to 4 if I'm doing my math correctly (4 worker processes + 1 master process) * 4 connections per process. (Note that for the purposes of this question I'm ignoring errors that occur around deploying, since I'm assuming Heroku might be connecting both old and new processes during that process, even though I'm not using Preboot.)

Where am I misunderstanding how this all fits together?

Rake command after deploy on Dokku

I'm running a RoR application with dokku on production.

What is the simplest way to automate and run a rake to clear my cache after every deploy?

Can I access rails app resources from Rails Engine or Mountable Engine?

I want to create a gem that is Rails Engine (or Mountable Engine). And it wants to list resouces from parent rails app.

For example:

# one rails app on routes
mount MyGem::Engine, at: '/my_gem' if Rails.env.development?

And when I access /my_gem, I want to list files from app/views/foo/xxxx, app/assets/my_gem/xxxx etc (not my gem views, assets).

giboon mailchimp 404 error

I am using the ROR Gem Gibonn by Amro for integration with mailchimp. I have followed the how-to at http://ift.tt/1mOZGRi. When I attempt to add a new subscriber I receive a 404 error "ResourceNotFound". Thing is I am not sure what "Resource" is not found.

Here is my _form.html.erb

<%= form_tag('/emailapi/subscribe', method: "post", id: "subscribe") do -%>
   <%= text_field(:FNAME, :fname, { placeholder: "First Name"}) %>
   <%= text_field(:LNAME, :lname, { placeholder: "Last Name"}) %>
   <%= email_field(:email, :email_address, { placeholder: "Email Address"}) %>
   <%= submit_tag("Sign me up!") %>

<% end %>`

Here is my emailapi_controller.rb

class EmailapiController < ApplicationController
def index
end

def subscribe
    @list_id = "3ea2e9a0c8"
    gb = Gibbon::Request.new

    gb.lists(:list_id).members.create(body: {
                                        email_address: "email_address",
                                        status: "subscribed",
                                        merge_fields: {
                                                        FNAME: "fname",
                                                        LNAME: "lname"
                                                        }
                                        })


   flash[:success] = "Thank you for pay-it-forward.
   You are now added to our email list."
   redirect_to '/'
end

end

How to reference a file outside of model in Rails?

I'm adding the carrierwave gem to an app in Rails, and I'm getting a weird NameError. I've followed all other posts on it, yet none of them worked. Here's the error:

uninitialized constant Post::ImageUploader

Extracted source (around line #2):
class Post < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

And post.rb:

class Post < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

Also, here's one site that I went to, but it didn't describe where to place the code, so I got really confused.

Can anyone help me figure out what's going on? Thanks.

Are there any recommended solutions for private key management in AWS?

I'm setting up PayPal integration with my Rails website and currently am using PayPal's stored button solution. That works just fine for the two subscription levels I currently have in place, but in anticipation of negotiated rates for our larger customers, I need to have a more flexible solution that doesn't involve creating a new button for every rate we negotiate--I need a secure way to pass the payment amount to PayPal.

The way to do this seems to be to use PayPal's encrypted buttons, which uses asymmetric key cryptography. This makes me shudder because, as I understand it, I then have to remember to regenerate a new public key every year. I then need to find a secure way to store my private key and make sure that any new instances that I spin up in my AWS ElasticBeanstalk environment will have that private key on hand (without checking it into source control, obviously).

I was thinking that AWS Key Management Service might be a promising solution for key management, but everything I've read thus far suggests that it would not solve the problem I'm facing.

Can anyone offer a best practice for how to manage private keys in AWS and how to make sure I don't get bit by an expired certificate?

Rails: Order by associate, first not downloaded

I have problem with displaying files. My app:

class User
   has_many :downloads
   has_many :downloaded_files, :through => :downloads, source: :file
end

class File 
   attr_accessor :downloaded

   has_many :downloads
   has_many :users, :through => :downloads
end

class Download
   belongs_to :user
   belongs_to :file
end

And when user log in i want to display all files but downloaded files by current user should be the last. The file table is about 500 records so i need simple and fast method. Have someone any idea ?

Rails 4.2.1 Ruby 2.2.2 Postgresql

Get a non-expiring, non-secure URL from S3 gem

My app uploads an image to S3 and returns the URL of that image. However, it returns a URL like http://ift.tt/1IVHbHu

How can I get it to return the simple URL that doesn't require access key and signature in the URL? Also, the links expire pretty quickly.

Here is my code:

bucket.objects[filename].write(result.to_blob, {:acl=>:public_read})
url = bucket.objects[filename].url_for(:read, :secure => false).to_s

How do I trigger a JS function from a js.erb executed as a callback on an AJAX call?

I know the title reads a bit funky, but this is what I am doing.

I have a link that looks like this, as defined in my nodes_helper.rb:

    link_to(favorite_node_path(node, node_counter: node_counter), class: "card-favorite-count favorited", method: :post, remote: true,  data: {toggle_href: unfavorite_node_path(node) }) do
      concat(content_tag(:i, "", class: "icon-heart"))
      concat(node.cached_votes_total)
    end

That then ultimately, on success, leads to this /views/nodes/favorites.js.erb being executed:

$("#card-<%= @node_counter %> .card-attr").html('<%= favorites_count(@node, @node_counter) %>');
$("#card-<%= @node_counter %> .card-attr").append('<%= comments_count(@node) %>');

All of that works fine, but what I want to do is add some animation to the class card-favorite-count after the link is pressed. Basically, right before the count gets updated.

My animation is defined in my app/assets/javascripts/nodes.js.coffee like so:

animate_favorite = ($favorite) ->
  $favorite.addClass 'active'
  card = $favorite.parent().parent().parent()
  card_id = card.attr('id')
  setTimeout (->
    $('#' + card_id).find('.card-favorite-count').removeClass 'active'
    return
  ), 1200
  return

$(document).ready ->
  $('.card-favorite-count').click ->
    animate_favorite $(this)
    return
  return

The JS version of the above works in a plain old vanilla HTML/JS interface, but I am trying to hook it up with everything else I have going on - hence the conversion to CoffeeScript.

So, how do I call that animate_favorite function, from within my favorite.js.erb?

Edit 1

Per Ryan's suggestion, I tried this in my favorite.js.erb:

window.animate_favorite($(this));
$("#card-<%= @node_counter %> .card-attr").html('<%= favorites_count(@node, @node_counter) %>');
$("#card-<%= @node_counter %> .card-attr").append('<%= comments_count(@node) %>');

But I get this error in my JS console:

window.animate_favorite($(this));
$("#card-1 .card-attr").html('<a class="card-favorite-count favorited" data-method="post" data-remote="true" data-toggle-href="/nodes/2/favorite" href="/nodes/2/unfavorite?node_counter=1" rel="nofollow"><i class="icon-heart"></i>1</a>');
$("#card-1 .card-attr").append('<span class="card-comment-count"><i class="icon-speech-bubble-1"></i>0</span>');

comments.self.js?body=1:5 parsererror

Rails 4 - Can't update model attribute

How can I save an attribute based on a condition between attributes of the same model? I've been unable to update a record unless the attribute's state remains the true.

I've checked this thread before: Rails. Update model attributes on save

This is the code I'm running:

class Ip < ActiveRecord::Base
  has_paper_trail
  has_and_belongs_to_many :users
  validates_uniqueness_of :ip_address, :hostname
  before_save :set_availability

  extend Enumerize
  enumerize :status, in: [:available, :allocated, :pending, :blocked], default: :available

  def ip_address_name
    self.ip_address
  end

  def set_availability
    self.is_available = false unless self.status.available?      
  end
end

Basically I have a list of "Ips" which I'd like to keep track of, and a "is_available" boolean to tell me wether the ip's status is available or not (which should set itself automatically, based on the "status" field).

So the issue is, for example,

I access the model, edit the record, change the :status from :available to :allocated, and hit "Save", it rolls back, raises me "Ip failed to be updated", and on the server the transaction is "Completed 406 Not Acceptable"

Here's the log:

=============== Phusion Passenger Standalone web server started ===============
PID file: /home/user/IP_Manager/tmp/pids/passenger.3000.pid
Log file: /home/user/IP_Manager/log/passenger.3000.log
Environment: development
Accessible via: http://0.0.0.0:3000/

You can stop Phusion Passenger Standalone by pressing Ctrl-C.
Problems? Check http://ift.tt/1M8YLs8
===============================================================================
App 31353 stdout: 
App 31368 stdout: 


Started HEAD "/" for 127.0.0.1 at 2015-08-04 09:41:07 -0300
  ActiveRecord::SchemaMigration Load (0.2ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by HomeController#index as HTML
Redirected to http://ift.tt/1E65L11
Completed 302 Found in 10ms (ActiveRecord: 0.0ms)


Started GET "/admin/ip/2/edit" for 127.0.0.1 at 2015-08-04 09:41:14 -0300
Processing by RailsAdmin::MainController#edit as HTML
  Parameters: {"model_name"=>"ip", "id"=>"2"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Ip Load (0.1ms)  SELECT  "ips".* FROM "ips" WHERE "ips"."id" = ?  ORDER BY "ips"."id" ASC LIMIT 1  [["id", 2]]
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_boolean.html.haml (2.4ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (1.2ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (0.2ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_enumeration.html.haml (2.7ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_text.html.haml (1.0ms)
  User Load (0.2ms)  SELECT "users".* FROM "users" INNER JOIN "ips_users" ON "users"."id" = "ips_users"."user_id" WHERE "ips_users"."ip_id" = ?  [["ip_id", 2]]
   (0.1ms)  SELECT COUNT(*) FROM "users"
  User Load (0.1ms)  SELECT "users".* FROM "users"  ORDER BY users.id desc
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_filtering_multiselect.html.haml (27.7ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_submit_buttons.html.haml (2.8ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/edit.html.haml within layouts/rails_admin/application (64.5ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_secondary_navigation.html.haml (3.7ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_navigation.html.haml (6.6ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_sidebar_navigation.html.haml (4.1ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/pjax.html.haml (7.3ms)
Completed 200 OK in 611ms (Views: 484.5ms | ActiveRecord: 1.6ms)


Started PUT "/admin/ip/2/edit" for 127.0.0.1 at 2015-08-04 09:41:20 -0300
Processing by RailsAdmin::MainController#edit as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"OI5LqfNXeYLQm1wGglmnPvkrTL3sHTYsiE/uJGp7Uxuserk7ee8b8ozIXclBkUtYYcoIeKCjcNnyZ00siruQjEZQ==", "ip"=>{"is_available"=>"1", "ip_address"=>"192.168.0.2", "hostname"=>"localhost2", "status"=>"allocated", "details"=>"", "user_ids"=>["", "", "1"]}, "return_to"=>"", "_save"=>"", "model_name"=>"ip", "id"=>"2"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Ip Load (0.1ms)  SELECT  "ips".* FROM "ips" WHERE "ips"."id" = ?  ORDER BY "ips"."id" ASC LIMIT 1  [["id", 2]]
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  User Load (0.1ms)  SELECT "users".* FROM "users" INNER JOIN "ips_users" ON "users"."id" = "ips_users"."user_id" WHERE "ips_users"."ip_id" = ?  [["ip_id", 2]]
   (1.1ms)  begin transaction
  Ip Exists (0.2ms)  SELECT  1 AS one FROM "ips" WHERE ("ips"."ip_address" = '192.168.0.2' AND "ips"."id" != 2) LIMIT 1
  Ip Exists (0.2ms)  SELECT  1 AS one FROM "ips" WHERE ("ips"."hostname" = 'localhost2' AND "ips"."id" != 2) LIMIT 1
   (0.1ms)  rollback transaction
  PaperTrail::Version Load (0.3ms)  SELECT "versions".* FROM "versions" WHERE "versions"."item_id" = ? AND "versions"."item_type" = ?  ORDER BY "versions"."created_at" ASC, "versions"."id" ASC  [["item_id", 2], ["item_type", "Ip"]]
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_boolean.html.haml (0.4ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (0.4ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (0.3ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_enumeration.html.haml (1.1ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_text.html.haml (0.5ms)
  User Load (0.2ms)  SELECT "users".* FROM "users"  ORDER BY users.id desc
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_filtering_multiselect.html.haml (5.0ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_submit_buttons.html.haml (1.5ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/edit.html.haml within layouts/rails_admin/application (25.7ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_secondary_navigation.html.haml (1.9ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_navigation.html.haml (3.6ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_sidebar_navigation.html.haml (2.6ms)
  Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/pjax.html.haml (6.1ms)
Completed 406 Not Acceptable in 267ms (Views: 223.5ms | ActiveRecord: 2.9ms)

This is my Gemfile (only the extra gems besides the default ones):

# Administration Panel Gems
gem 'rails_admin'                    # Rails Administration Panel Gem
gem 'rails_admin_history_rollback'   # Enables users to visualise and revert history
gem 'rails_admin_import', "~> 1.0.0" # Enables importation
gem 'devise'                         # Authentication Gem
gem 'cancancan'                      # Authorization Gem
gem 'paper_trail', '~> 4.0.0.rc'     # Auditing Gem (History)
gem 'enumerize'                      # Gem for enumerizing attributes

# Server gem
gem 'passenger'

Thank you for your time!

"resources :post, except: :new" makes Rails think the route /posts/new would point to a post ID "new"

I have the following route:

resources :success_criteria, except: :new

The following spec fails:

describe SuccessCriteriaController do
  describe 'routing' do
    it 'routes to #new' do
      expect(get('/success_criteria/new')).to_not be_routable
    end
  end
end

Failure message:

Failure/Error: expect(get('/posts/new')).to_not be_routable
expected {:get=>"/posts/new"} not to be routable, but it routes to {:controller=>"posts", :action=>"show", :id=>"new"}

The controller looks like this:

class SuccessCriteriaController < InheritedResources::Base
  load_and_authorize_resource
end

Why does Rails think that posts/new would point to a post with the ID new? That's not right, is it? Does it maybe have to do with InheritedResources?

PG::SyntaxError for rails application

IN my index controller I have a query to find all past events which have happened where "when is the date the event has took place

@expired = Location.where('when <= ?', Date.today)

This is my index.html.erb view.

<% @expired.each do |location| %>
               <tr>
                <td>
                  <%= location.city %>                                                                                                                                                                                  
                </td>
                <td><%= location.when %>
                </td>
                <td><%= location.venue %></td>
                <td>
                  <%= location.start_time %> to <%= location.end_time %>
                </td>
                <td>General</td>
                <td><a href="http://ift.tt/1E65L0W" target="_blank">Smithridge Healthcare</a></td>
              </tr>
<% end %> 

When I run the server I get this following error:

PG::SyntaxError: ERROR:  syntax error at or near "when"
LINE 1: SELECT "locations".* FROM "locations" WHERE (when <= '2015-0...

Could it be due to the wrong formatted date?

Allowing admin and users to sign in using same form (rails)

I've created 2 tables, one for users and one for admins.

I created 2 tables as they both collect different information, but I want to be able to allow a sign in using an email address and password from both the admin and user tables via the same form.

Is this possible? I've looked around and people seem to have created 1 users table and added an admin boolean, but I wanted to avoid this and I didn't want to collect unnecessary data if I didn't need to.

Any help and assistance about how to best go around this would be great.

Rails - DRY similar methods? [migrated]

In order to reduce redundancy in my app, I have added the method self.find_or_keep(object) to many of my models in order to find existing records with the same values, so I can reference the already existing ones instead of creating new records. Basically, what the method does is checking most attributes for equality between two objects; id, created_at and updated_at are always excluded for obvious reasons.

class IPv4 < ActiveRecord::Base
  # returns its param or an already existing record
  def self.find_or_keep(ipv4)
    # create new object in memory, if param is a Hash
    ipv4 = IPv4.new(ipv4) if ipv4.is_a?(Hash)
    return (entry = IPv4.find_by(address: ipv4.address, subnetmask: ipv4.subnetmask)) ? entry : ipv4
  end
end

class Service < ActiveRecord::Base
  # returns its param or an already existing record
  def self.find_or_keep(service)
    # create new object in memory, if param is a Hash
    service = Service.new(service) if service.is_a?(Hash)
    return (entry = Service.find_by(protocol: service.protocol, port_from: service.port_from, port_to: service.port_to)) ? entry : service
  end
end

As you can see, not very DRY. The problem here is, that the method each time has to check for different parameters, so I have to rewrite the find_by every time I want to use the method in another class. What I have in mind for DRYing it up is something like this:

class IPv4 < ActiveRecord::Base
  implement_find_or_keep_with(:address, :subnetmask)
end

class Service < ActiveRecord::Base
  implement_find_or_keep_with(:protocol, :port_from, :port_to)
end

class ActiveRecord::Base
  # whatever is need
end

Is something like this possible and if so, how would I implement it?

new_path url is showing correctly in address bar but displaying a different page

I'm having a problem where my link to orders#new is bringing up the right url in the browser but is rendering what looks like orders#index but with no entries in it.

Here are my routes, I'm wondering if I've got a problem with the priorities in them?

  get 'loans/stock' => 'loans#stock'
  resources :loans
  get 'parts/all' => 'parts#view', :as => :parts_all
  get 'orders/:region' => 'orders#region', :as => :orders_by_region
  get 'orders/:printer/parts' => 'orders#printerparts', :as => :parts_by_printer
  resources :orders do
    resources :parts
  end
  resources :parts

EDIT I've taken the below advice and resorted my routes but it seems whatever I do something breaks. I have a link for my orders filtering by region and the filter to show parts belonging to an order by it's printer.

If I move the region route down it stops working. If I leave it where it is, the new and show actions won't work for orders. Maybe I've just done something completely wrong in my setup?

Refactoring multiple render in controller

In my rails controller, I have to check after getting @group with before_action that this group is not system.

But I have lot's of repetition in my controller. I've tried to turn into a separate method but I get the classic :

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".

Here is a part of my code

def destroy
  if @group.is_system?
    render json: { errors: 'You can\'t delete a group system' }, status: 403
    return
  end

  ...
end

def update
  if params[:group] && !params[:group].empty?
    if @group.is_system?
      render json: { errors: 'You can\'t edit a group system' }, status: 403
      return
    end

    ...

  else
    render json: { errors: 'Missing correct parameters' }, status: :unprocessable_entity
  end
end

.....

Rails transfer form data modification error

I have a form in which I input a transfer. This transfer is stored into a database (and used for a transaction in the controller).

It worked roughly, but now for the finetuning the input needs modification before I save or a transaction is made.

  • The name of the recipient needs to be a transformed into this users id.
  • The amount has a two decimal number input and should be modified to cents by multiplying it by a hundred and making it an integer. Banks need a solid integer basis as you know.

I thought this could work:

Transfer model

  #transfer.rb
  has_one :sender,
          :class_name => "User", 
          :foreign_key => "sender_id"
  has_one :recipient, 
          :class_name => "User", 
          :foreign_key => "recipient_id"

  validates :sender_id, presence: true
  validates :recipient_id, presence: true
  validates :amount, numericality: {:greater_than => 0}

  before_validation :recipient_name_to_id 
  before_validation :amount_to_cents

  def recipient_name_to_id
    recipient = User.find_by_user_name(self.recipient_id)
    self.recipient_id = recipient.id
  end

  def amount_to_cents
    cents = self.amount
    cents = cents*100
    cents.to_i
    self.amount = cents 
  end

To modify the :recipient_id and the :amount taken from the form while the app asks for a name and any number.

It doesn't work, because in the transaction it can't find the recipients banksaldo.

NoMethodError in TransfersController#create

undefined method `cents' for nil:NilClass

 @account_b.cents += @transfer.amount

Everything else works fine. I checked it thoroughly.

But maybe it helps to add the controller

TransfersController

  def create
    @user = User.find(params[:user_id])
    #transfer
    @transfer = Transfer.new(transfer_params)
    @transfer.sender_id = @user.id

    #transactie tussen accounts
    @account_a = @user.account
    @account_b = Account.find_by_user_id(@transfer.recipient_id)
      if @account_a != @account_b
        if @account_a.cents >= @transfer.amount
          Account.transaction do
              @account_a.cents -= @transfer.amount
              @account_a.save!
              @account_b.cents += @transfer.amount
              @account_b.save!
              @transfer.save!
              flash.notice = "Uw opdracht is verzonden."
          end
        else
          flash.notice = "U beschikt niet over voldoende saldo om uw opdracht te doen slagen."
        end
      else
        flash.notice = "U kunt geen geld overmaken naar uw eigen account."
      end
    redirect_to user_path(@user)
  end

  private
  def transfer_params
    params.require(:transfer).permit(:sender_id, :recipient_id, :amount)
  end

Update

I am now working with current setting (is this more clever, or does it not really matter?).

#same transfer.rb model but now with this as non private methods.
def recipient_id=(value)
  user = User.find_by_user_name(value)
  self[:recipient_id] = user.id 
end

def amount=(value)
  cents = value * 100
  cents.to_i
  self[:amount] = cents
end

The code now gives:

Validation failed: Amount is not a number

and can't @transfer.save! in the controller.

Update 2

All right it nearly works. I had to make the value into a float first by to_f. Then it worked... until I turned on the validation again (which I commented out) and now it gives an error that amount is not an integer... Which I state in the def. Hmprff :S

Update 3

It all works now. My methods look like this now:

  def recipient_id=(value)
    user = User.find_by_user_name(value)
    self[:recipient_id] = user.id 
  end

  def amount=(value)
    cents = value.to_f * 100
    self[:amount] = cents.to_i
  end

Bad thing about it is that with wrong form information the app gives it's validation error screen, while I want it to give a notice and redirect it to the show window where it was.

It can't find both methods flash and redirect in these methods I defined above in the transfermodel.

How can i generate json response from rabl gem and money gem with the database table i have ?

This is the json i want to build from rabl gem

M-0 {"revenue":"value", "fee":"value", "created":"count", "paid":"count", "partially_paid":"count"},
M-1 {"revenue":"value", "fee":"value", "created":"count", "paid":"count", "partially_paid":"count"},
M-2 {"revenue":"value", "fee":"value", "created":"count", "paid":"count", "partially_paid":"count"},
M-3 {"revenue":"value", "fee":"value", "created":"count", "paid":"count", "partially_paid":"count"},
M-4 {"revenue":"value", "fee":"value", "created":"count", "paid":"count", "partially_paid":"count"},
M-5 {"revenue":"value", "fee":"value", "created":"count", "paid":"count", "partially_paid":"count"}

This is my database table

create_table "merchant_monthly_stats", force: true do |t|
    t.integer  "created_count",        default: 0
    t.integer  "ready_count",          default: 0
    t.integer  "paid_count",           default: 0
    t.integer  "partially_paid_count", default: 0
    t.integer  "cancelled_count",      default: 0
    t.integer  "failed_count",         default: 0
    t.integer  "processed_count",      default: 0
    t.integer  "expired_count",        default: 0
    t.integer  "merchant_id",                          null: false
    t.integer  "year",                                 null: false
    t.integer  "month",                                null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "overdue_count",        default: 0
    t.integer  "fee_centimes",         default: 0,     null: false
    t.string   "fee_currency",         default: "XAF", null: false
    t.integer  "revenue_centimes",     default: 0,     null: false
    t.string   "revenue_currency",     default: "XAF", null: false
  end

This is my controller method

def history
    current_month = Time.now.month
    current_year = Time.now.year
    list_of_last_six_months = [current_month]
    5.times do |i|
      list_of_last_six_months << (current_month - i )
    end 

    month_array =[]
    list_of_last_six_months.each { |month|
      record = MerchantMonthlyStat.find_by merchant_id: current_api_user.id, year: current_year, month: month
      m = { 
        :revenue => Money.new(record.revenue_centimes , record.revenue_currency).format,
        :fees => Money.new(record.fee_centimes,record.fee_currency).format, 
        :created => record.created_count , 
        :paid => record.paid_count , 
        :partially_paid => record.partially_paid_count }
      month_array.push(m)
    }
    respond_with(month_array, status: :ok, template: 'api/merchant/mobiles/history')
  end

My question is how do i write the rabl template 'api/merchant/mobiles/history' to get the above json response ?

Note : I am using rails money gem. Thats why there is Money.new etc

Rails fails to connect to mysql server if I add some default character and collate settings for mysqld

I habe install rails and everything else needs onto a new CentOS 7 server. I have create mysql database via command line and then I've edited it to use character set utf8 and collation utf8_general_ci.

Rails worked.

Then I configured /etc/my.cnf to include some default settings for charset and collation:

[mysqld]
character-set-server = utf8
collation-server = utf8_general_ci
init_connect=‘SET collation_connection = utf8_general_ci’

[client]
default-character-set = utf8

Rails stopped working saying it can't connect to the mysql.

Obviously, I could reconfigure something in Rails to solve this, but I don't know what.

Thanks for the help.

phone number validation regex in rails

Hi I need to validate phone number in these formats +1-541-754-3010 , (123) 986-5470 and 123-569-8740 I have given following regex

validates :phone, format: { with: /\A\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}\z/,
                              message: I18n.t('global.errors.phone_format')}

It working for (123) 986-5470 and 123-569-8740 but not for +1-541-754-3010. Please guide me how to solve this.Thanks in advance

Testing a Rails password change form

I'm new to rails, and testing is still a bit mysterious to me. I searched unsuccessfully for a way to test forms without adding gems. Here's what I'm trying to do.

My form has old_password, new_password, and confirm_password fields.

<%= form_for @user, :url => "change_password" do |f| %>
    <%= f.label :Current_Password %>
    <%= f.password_field :old_password, class: 'form-control' %>
    <%= f.label :New_Password %>
    <%= f.password_field :new_password, class: 'form-control' %>
    <%= f.label :Confirm_Password %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>
    <%= f.submit "Change Password", class: "btn btn-primary" %>
<% end %>

My routes

 # Users
  resources "users"

  patch 'users/:id/change_password' => 'users#change_password'

My users controller action

  def change_password
    # Change password.
    @user = User.find(params[:id])
    if @user and @user.authenticate(params[:user][:old_password])
      if params[:user][:new_password] == params[:user][:password_confirmation]
        @user.update_attribute(:password_digest, 
            User.digest(params[:user][:new_password]))
        flash[:success] = "Password changed sucesfully."
        redirect_to @user
      else
        flash.now[:danger] = "Password and confirmation do not match."
        render 'edit'
      end
    else
      flash.now[:danger] = "Incorrect password."
      render 'edit'
    end
  end

My test. It is very similar to the test from the Rails Tutorial. This is the piece I don't understand.

  test "password change wrong password" do
    get edit_user_path(@user)
    assert_template 'users/edit'

    # Submit wrong password.
    patch user_path(@user), user: { old_password: "invalid",
                                    new_password:  "foobar11",
                                    password_confirmation: "foobar11" }

    # Flash not empty.
    assert_not flash.empty?

    # Redirected to edit page.
    assert_template 'users/edit'

    # Password not changed in database.

  end

The test fails on assert_template 'users/edit'

expecting <"users/edit"> but rendering with <[]>

When I run my rails4.0 app with ruby 1.9.3 getting uintptr_t error

cparser.rb:104:in `parse_ctype': unknown type: uintptr_t (DL::DLError)

Suddenly I am getting this error when I run my rails app. Anyone have any idea on when these kind of error will come?

C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/1.9.1/dl/cparser.rb:104:in `parse_ctype': unknown type: uintptr_t (DL::DLError)
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/1.9.1/dl/cparser.rb:33:in `block in parse_struct_signature'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/1.9.1/dl/cparser.rb:9:in `each'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/1.9.1/dl/cparser.rb:9:in `parse_struct_signature'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/1.9.1/dl/import.rb:183:in `struct'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/pageant.rb:157:in `<module:Win>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/pageant.rb:39:in `<module:Pageant>
'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/pageant.rb:31:in `<module:Authenti
cation>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/pageant.rb:22:in `<module:SSH>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/pageant.rb:22:in `<module:Net>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/pageant.rb:22:in `<top (required)>
'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/agent/socket.rb:5:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/agent/socket.rb:5:in `<top (requir
ed)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/agent.rb:22:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/agent.rb:22:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/key_manager.rb:4:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/key_manager.rb:4:in `<top (require
d)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/session.rb:4:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh/authentication/session.rb:4:in `<top (required)>'

        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh.rb:11:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/net-ssh-2.10.0/lib/net/ssh.rb:11:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/fog-1.32.0/lib/fog/joyent/compute.rb:3:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/fog-1.32.0/lib/fog/joyent/compute.rb:3:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/fog-1.32.0/lib/fog/joyent.rb:1:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/fog-1.32.0/lib/fog/joyent.rb:1:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/fog-1.32.0/lib/fog.rb:41:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/fog-1.32.0/lib/fog.rb:41:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/carrierwave-0.10.0/lib/carrierwave/storage.rb:5:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/carrierwave-0.10.0/lib/carrierwave/storage.rb:5:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/carrierwave-0.10.0/lib/carrierwave.rb:78:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/carrierwave-0.10.0/lib/carrierwave.rb:78:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/runtime.rb:76:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/runtime.rb:72:in `each'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/runtime.rb:72:in `block in require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/runtime.rb:61:in `each'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/runtime.rb:61:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/bundler-1.10.5/lib/bundler.rb:134:in `require'
        from C:/Vinothini/Projects/GSS/snapshot/config/application.rb:12:in `<top (required)>'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/commands.rb:43:in `require'
        from C:/MotorolaRhoMobileSuite4.0.0/ruby/lib/ruby/gems/1.9.1/gems/railties-4.0.2/lib/rails/commands.rb:43:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

Overriding RSpec generator template

Trying override the default rspec-rails scaffold generator template for controllers but for some reason the new template isn't getting picked up

/lib/templates/rspec/scaffold/controller_spec.rb

Apparently putting it there should just work but it still doesn't show when running rails g rspec:scaffold.

Did the format change? I'm using Rails 4.2.2 and rspec-rails 3.3.3

LIT + Casein + authlogic

I'm trying to integrate LIT http://ift.tt/1Fzw2Vq in a casein CMS install http://ift.tt/WlceWt

Casein uses authlogic for user authentication, to use the same sessions, casein can be configured to use the app's authentication function. It gives the example ":authenticate_user! "

# in config/lit.rb
# Which authentication function to use (ie. :authenticate_user!)? When set to
# `nil` will let everyone in.
Lit.authentication_function = :authenticate_user!

It seems like I should be familiar with this authentication function's name, I tried to search the casein and authlogic source without luck.

Thanks for your help

Cucumber/Capybara tests returning Addressable::URI::InvalidURIError when I visit url

I am unable to visit the following url "http://localhost:7000/login/next=" In my page object i have set the following:

class LoginPage < SitePrism::Page
    set_url "/login/next="

and I have set the following in my env.rb file

Capybara.app_host = "http://localhost:7000"
Capybara.server_host = "localhost"
Capybara.server_port = "7000"

and required the following:

require 'uri'
require 'net/http'
require 'open-uri'

When I run test it get the following

Cannot assemble URI string with ambiguous path: ':7000/login/next='(Addressable::URI::InvalidURIError)

Capybara doesn't like the port/host in the url. Any ideas who to get rounds this please?