mardi 4 août 2015

Ruby2.0: What is the difference between Ruby Refinements and Monkeypatches?

I could do some simple task in either way,

Refinements

module StringRefinements
  refine String do
    def do_something
      "bla bla bla..."
    end
  end
end

So, I can use do_something method wherever StringRefinements module was using.

Monkeypatch

class String
  def do_something
    "bla bla bla..."
  end
end

I would like to know the difference between Ruby's new concept Refinements and the one Monkeypatch. And what are the advantages of using Refinements over Monkeypatch?



via Chebli Mohamed

What is a good way to suppress 304 responses in Rack?

Rack seems to use the If-Modified-Since header. So one way to suppress 304 responses is to delete this header.

Is this a good way to suppress 304 responses? Is there a better way?



via Chebli Mohamed

Rails controllers architecture with many to many relationships

I am developing a portal via RubyOnRails where pupils, teachers and parents can participate in different contests with their art works.

There are 3 entities: Contests, Categories (competitor categories / age groups) and Nominations (kinds of activity). Contest can have many Categories. Each ContestCategory can have many Nominations. Each Category can belong to several Contests. Every Nomination can belong to many ContestCategories. So I presume there is many-to-many relationship between Contests and Categories and many-to-many relationship between ContestCategories and Nominations. I've created following models: Contest (contest.rb), Category (category.rb), Nomination (nomination.rb), ContestCategory (contest_category.rb) and ContestCategoryNomination (contest_category_nomination.rb).

My models:

class Category < ActiveRecord::Base
  has_many :contest_categories
  has_many :contests, through: :contest_categories
end

class Contest < ActiveRecord::Base
  has_many :contest_categories
  has_many :categories, through: :contest_categories
  has_many :nominations, through: :contest_categories
  has_one :provision
end

class ContestCategory < ActiveRecord::Base
  belongs_to :contest
  belongs_to :category
  has_many :contest_category_nominations
  has_many :nominations, through: :contest_category_nominations
end

class ContestCategoryNomination < ActiveRecord::Base
  belongs_to :contest_category
  belongs_to :nomination
end

class Nomination < ActiveRecord::Base
  has_many :contest_category_nominations
  has_many :contest_categories, through: :contest_category_nominations
  has_many :contests, through: :contest_categories
end

I want to create an ajax-based modal window during creation of new Contest to link it with Category and select multiple Nominations that belong to this Category.

  1. What controllers should I create to satisfy has_many relationships between my models?
  2. What are the naming conventions (singular and plural) in rails to satisfy my relationships? For example, ContestsCategoriesController or ContestCategoryNominationsController or may be ContestCategoryNominationsController?
  3. What action method should I create in this controllers to invoke to render this modal window? Should it be new_category action in CategoriesController or new action in ContestsCategoriesController or new action in ContestsCategoriesNominationsController?


via Chebli Mohamed

Ruby on Rails: if current page? is homepage, don't show form

I want to not show a form, but only if current page is NOT the home page

This is what I have so far...

I have my route setup:

root 'projects#index'

My view:

<% if !current_page?(url_for(:controller => 'projects', :action => 'index')) %>
  show some stuff
<% end %>

This doesn't show if the url is localhost:3000/projects

But it shows if its localhost:3000

So I need to somehow make sure that if its the homepage, it won't show. Also, I have search parameters for the home page, and I still don't want to show if its like localhost:3000/projects?search=blahblahblah



via Chebli Mohamed

Trying to reference earlier 'case' in a case statement

When someone tries to update a value that is not currently stored in my hash, I would like to immediately reference back to "when 'add'" without restarting the entire case statement (since I already know they want to add and don't want to prompt them again). Is there a way to reference back to the case choice -> when "add" section of my code without restarting the entire case statement? I know I could use nested case statements but I would rather not copy/paste identical code if I don't have to.

Also, sorry for the abrupt ending of the code. I just didn't want to put in anything unnecessary to the solution.

    hash = {}
    puts "Would you like to add or update this hash?"
    choice = gets.chomp
    case choice
    when "add"
      puts "What key you like to add?"
      key = gets.chomp
      puts "With what value?"
      value = gets.chomp
      hash[key] = value
    when "update"
      puts "Which key would you like to update?"
      key = gets.chomp
      if hash[key].nil?
        puts "Key not present, would you like to add it?"
        #here I would like the code that references back to "when 'add'" if the user types 'yes'    



via Chebli Mohamed

Nested forms using the Cocoon gem in Ruby on Rails 4.2

I'm building a web app using Rails 4.2 and I have a model called Strategy which has a has_many relationship to a Tactic model.

To create a view for Strategy, I need to have many nested Tactics on the form. I've been using the Cocoon gem to develop this view.

So far, I've been able to get the form to work properly for the most part but the issue is that I wanted to add a Type attribute to my Tactic model.

For a given strategy, I want to have 3 tactics of one given type, and 2 models of another.

The issue is that rendering my view, all five models are listed sequentially without any room for putting in my own HTML code around them.

Is there a simple way to separate out which of these are rendered? Right now, my view looks as follows...

<%= form_for @strategy do |f| %>
    <div class="strategy">
        <%= f.label :name %>
        <%= f.text_field :name %>
    </div>

    <div class="tactics">
        <%= f.fields_for :tactics do |i| %>
            <%= render 'tactics_fields', f: i %>
        <% end %>
    </div>

    <div class="buttons">
        <%= f.button "Save Strategy", class: 'button' %>
    </div>
<% end %>

If anyone can offer any advice, it would be greatly appreciated.



via Chebli Mohamed

extend array by n numbers while repeating elements

If I have an array like this

[1,2,3]*2 
#=> [1,2,3,1,2,3,1,2,3]

But I want to do it to certain length, that length is 1.5 the original array, preferably in one line

[1,2,3].size = 3
[1,2,3,1,2] or something like this



via Chebli Mohamed

Unable to run node_modules/.bin/browserifyinc. Ensure you have installed it with npm

Unable to run node_modules/.bin/browserifyinc. Ensure you have installed it with npm. (in /Users/labuser/Downloads/betfair_nav_demo-master/app/assets/javascripts/application.js)

I am using Ampersand JS with Rails application. gem 'rails', '4.2.1' gem "browserify-rails", '1.2.0'

I have installed npm install ampersand -g

npm install browserify --save-dev

npm install underscore --save

My Rails app is working without browserify-rails gem.



via Chebli Mohamed

Rails ActiveRecord - querying on last record of relationship

I have a model Book with a has_many relationship to State.

class Book < ActiveRecord::Base
   has_many :states
   ...
end

State sets the visibility of the book to "private", "restricted" or "public" through a name attribute. For auditing purposes, we keep a record of all state changes so to get the current state of a book I use

> book = Book.first
> book.states.last.name
> "public"

Now I need to query on all Book objects where the current state is public.

Something along the lines of:

Book.joins(:visibility_states).where(states: { state: "public"})

The problem is that the query above return all books that are currently pubic, or have been public in the past. I only want it to return books that are currently "public" (i.e. book.states.last.name == "public").

I know I can do it with select but that's generating one query for each record:

Book.all.select { |b| b.states.last.name == "public" }

Is there a way to do it using ActiveRecord only?



via Chebli Mohamed

Convert Jira's time tracking field format to hours

I am using JIRA api to extract timespent by users on issues. The time spent is in the format:

"12w 1d 2h 5m" or "12h" or "12m" etc

The API isn't exporting the number of hours. Is there a quick (requires no effort on my part) way to convert this to hours (or seconds). I suppose this is some sort of a standard format, is there a name for it? I know how to do this myself, just don't want to reinvent the wheel



via Chebli Mohamed

Cannot fnd bson_ext in path

I am getting the highly poular message:

** Notice: The native BSON extension was not loaded. **

For optimal performance, use of the BSON extension is recommended.

To enable the extension make sure ENV['BSON_EXT_DISABLED'] is not set
and run the following command:

  gem install bson_ext

If you continue to receive this message after installing, make sure that
the bson_ext gem is in your load path.

I am running rbenv and have tried gem install bson_ext. I get no errors - it tells me Successfully installed bson_ext-1.12.3. However bson_ext is not found - I assume its an executable. How do I know where it should be installed so that I can update my path accordingly?

If I search in my local .rbenv dir I see:

.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bson_ext-1.12.3/ext/bson_ext/bson_ext/

But do not see anything that appears to be an executable.



via Chebli Mohamed

difference between calling super and calling super()

What is the difference between calling super and calling super()? Which is the best one if the arguments passed to the child method don’t match what the parent is expecting.



via Chebli Mohamed

Unable to send mail with attachment using Mandrill-api gem (Rails 4.1)

Emails without attachment are delivered fine, but when there is an attachment I get the following error in production:

ArgumentError: An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.

  • Letter opener in dev model shows the email rendering perfectly
  • This error only shows up in production

the call to mailer is:

# template variables
merge_vars = {"AMOUNT" => "100"}

invoice = Invoice.new(customer)

attachments[invoice.name] = {
  data: invoice.invoice_data,
  mime_type: 'application/pdf'
}

mail(to: user.email, cc: cc_emails.compact.uniq, subject: mail_subject, content_type: content_type) do |format|
  # Template renders fine
  format.html{mandrill_template('invoice_template', merge_vars)}
end

InvoiceMailer < ActionMailer::Base has defaults for "from" and "reply_to"

Mandril gem version 1.0.53 and Rails 4.1.10.



via Chebli Mohamed

Gem "Malformed Version Number String"

I'm building a gem. I just got the basic project structure laid out, and I tried building it with gem build my_gem.gemspec, which worked fine. Then I installed it with gem install My\ Gem-0.0.1.gem and it still looked like it worked fine. Then I tried to run irb and I got this:

/Users/<username>/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/version.rb:206:in `initialize': Malformed version number string on (ArgumentError)

Then I tried making some changes and saved them. I ran gem build my_gem.gemspec. Same error. All irb, rails, and gem sub-commands are generating a stack trace with this at the top. What did I do to break all of these commands and how do I reverse it?



via Chebli Mohamed

Is it possible to set Ruby ENV with bash in Chef?

I have a Chef recipe in which I am creating a new randomly named user using a shell script and exporting the username as a variable. Is it possible to set the same user as a session variable in Ruby? Something like...

ENV['CHEFUSER'] = 'echo $CHEFUSER'

which does not work unfortunately. Or any way to pass environment variables from bash to ruby. I need this new user to be recognized in the same recipe in which it was created.

Thanks, sorry if this has been addressed, I could not find any info on it.



via Chebli Mohamed

Paperclip S3 Bucket and Rails Images will upload but will not display

I am using paperclip gem along with an AWS s3 bucket to upload images to my app. I have it all working properly and the images will upload to the actual bucket and the web pages will load. The only problem is the images themselves will not display and it will only display their names like enter image description here

to display the image I am using the code

<%= image_tag @post.image.url(:medium), class: "edit_recipe_image" %>

has any one experiences this before or possibly know a solution to fix this?

Thanks in advance!



via Chebli Mohamed

how to stub specific IDs only in cucumber test?

Very new to Ruby and cucumber, and i've got a controller that accepts an ID. Basically a rest API, so the client would call /cows/1234 and /cows/777. That would then route to getFluffyCow and pass :id = 1234 or 777.

My initial attempt is as follows:

allow(getFluffyCow).to receive(:call).with(1234).and_return(mock_cow1)
allow(getFluffyCow).to receive(:call).with(777).and_return(mock_cow2)

but the response is returning nothing. What am I doing wrong?

Thanks!



via Chebli Mohamed

attr_accessible error on rails 4.1.8 upon performing rake db:migrate on heroku

I am still learning Ruby (so I am a complete noob), right now I have my app successfully running locally but when trying to opening the apps on heroku , in which I first perform the heroku run rake db:migrate I stumbled upon a problem.. it tells me :

Running `rake db:migrate` attached to terminal... up, run.2149
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice,  :pCategory, :pPic)
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice, :pCategory, :pPic)
rake aborted!
NoMethodError: undefined method `attr_accessible' for #<ActiveRecord::Migration:0x007f2dc2ba45b8>
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:648:in `block in method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `block in say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:641:in `method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:406:in `method_missing'
/app/db/migrate/20150802134246_create_inventories.rb:2:in `<class:CreateInventories>'
/app/db/migrate/20150802134246_create_inventories.rb:1:in `<top (required)>'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `block in require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:232:in `load_dependency'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:761:in `load_migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:757:in `migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:752:in `disable_ddl_transaction'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:1044:in `use_transaction?'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:954:in `rescue in block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:951:in `block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `each'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:807:in `up'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:785:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/railties/databases.rake:34:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:migrate

I have been trying to find out the reason, after wondering around I found out about change in rails 4.0.0 in that attr_accessible are no longer used and we should use strong parameter instead, So removing the attr_accessible from model will solve the problem...

However, I have an empty Model, there is no attr_accessible everywhere i look. (beside this is weird why my apps runs locally but not on heroku?) I can't figured out why this error appear and where to look for solutions.. I have been trying to look at active_record file but am afraid of making any changes, any idea?

also, could anyone tell me any resources that can help me read this type of log errors? I have tried to read some articles but can't find one that is easy to understand for noobs like me... ;(



via Chebli Mohamed

Excluding/Including items from one array based on values from another

I have two arrays, one containing hashes, the other integers. They look like this (samples):

mainArray[0] = {"ID" => 23, "NAME" => "SALLY"}
mainArray[1] = {"ID" => 34, "NAME" => "BILL"}

idArray[0] = 432
idArray[1] = 34

I want to filter mainArray so that only entries in it whose ID values are in idArray make the cut. How can I best do this? I don't mind making a new array if that helps.



via Chebli Mohamed

How do I call exposed methods in C# DLL from Ruby on Linux using Mono?

I have a DLL which contains code that I would like to access from Microsoft Visual Foxpro as well as Ruby on Rails.

I set up a C# DLL and generated the corresponding .so file using Mono according to this question. mono --aot -O=all dlltest.so

As noted in that question, the function nm -Ca dlltest.so shows a form of my method, but FFI cannot see it.

Also as mentioned in that question, nm -D --defined-only dlltest.so indicates that my method is not defined. However, FFI can see and access the one that is defined as mono_aot_file_info.

It seems like the poster of that question was close to getting it to work, but I was unable to find anything about why the method is showing as not defined or how to change that.

Is there something I can do to define the methods in the .so file? Or is this not possible?

Note that the method is exposed in the DLL, and FoxPro can access it just fine.



via Chebli Mohamed

Ruby on Rails frontend and Java backend architecture?

I am building a Ruby on Rails webapp and it is great for the web front end, display, what the user sees etc. But I want request from a user that involves some heavy processing to be done inside a Java backend layer.

So my question what do you think is the best approach for joining these two layers up? I can think of two approaches:

  1. Building up the request into a JSON object in the Ruby on Rails layer and using RabbitMQ to send it as a message to the Java backend layer which sends another JSON object back in a message as a response. I tend to lean more towards this approach as there a nice RabbitMQ clients for Ruby and Java.

  2. Have a my Java layer running on a web server(such as Tomcat or maybe Netty?) that accepts HTTP requests from the Ruby on Rails layer and sends the response back through the server using HTTP?

Note any persistence will be handled by the Java layer also.

Any more ideas or and/or comments on the above two ideas would be great.

Thanks.



via Chebli Mohamed

In RubyMine How do I Reset the Current Stack Frame?

In IntelliJ IDEA, or Eclipse, while working with java I am able to reset the current stack frame while debugging. For example, if I am debugging a method and I make some changes or want to go back and look something over I can reset the current stack frame and the debug pointer will go back to the beginning of the method. Is there anything like that in RubyMine?



via Chebli Mohamed

Allow users to sort images based on category selected (paperclip gem) - Rails

Currently my home page (index.html.erb) shows all the user images loaded within the past 24 hours, which is part of posts. However I would like to add a form that allows the user to sort images based on their category and upload date. (For example images with the category music, uploaded within the past month) I understand how to query the database but I dont know how to take the user input. When I create a form, suing simple form: <%= simple_form_for @posts do |f| %>, it throws an error, saying I cannot use an object. Ive thought about ajax but it doesnt seem to work well with the paperclip gem, plus I rather get it done on the backend. I hope my issue well enough. If not feel free to comment as I will be around to respond. Thanks in advance.

Post Controller:
 def index  
 @posts = Post.all.where(created_at:(Time.now - 1.day)..Time.now)
 end

Schema for Post table:

create_table "posts", force: :cascade do |t|
t.string   "title"
t.string   "instagram"
t.text     "description"
t.datetime "created_at",                            null: false
t.datetime "updated_at",                            null: false
t.integer  "user_id"
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"



via Chebli Mohamed

Failing to use numeric characters within Ruby array as indices for a string

I am trying to use the numeric charecters from the array held within the positions argument as indices to access the characters of the string inside the string argument to subsequently print a new string. I have an idea of what I need to do to get it to work, but I am hung up.

Total code thus far:

  def scramble_string(string, positions)
    str = string
    pos = positions.join
    newstr = []
    i = 0
    while i < pos.length do
      return newstr.push(str[pos[i]])
      i += 1
    end
  end
  scramble_string("hello", [2, 3, 4, 5])

I suspect my problem lies within this part of the code...

return newstr.push(str[pos[i]])



via Chebli Mohamed

Ruby - DOS (Win32) path name to NT (native) path name

I need to get the NT (native) path of a file from the DOS (Win32) path in Ruby (1.9.3).

Meaning, I have the string:

dos_path = "C:\Windows\regedit.exe"

but I need:

nt_path = "\Device\HarddiskVolume1\Windows\regedit.exe"

Is there any way to do so? Thanks!



via Chebli Mohamed

Why weakly typed languages would not need abstract classes?

Someone told me that the reason why Ruby does not implement abstract classes (you have to implement it yourself using some intelligent tricks) is that it isn't strongly typed. Can anybody explain that to me?



via Chebli Mohamed

Error while installing Sass on Win8.1: "ERROR: While executing gem (Errno::EACCES) Permission denied @ rb_sysopen"

I installed Ruby via the official installer, installed the non x64 version just in case. Then I tried to install sass via the command line like on the http://ift.tt/1f0fI2t page, The following ensued:

sgarcia C:\Users\sgarcia
> gem install sass
Fetching: sass-3.4.16.gem (100%)
ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied @ rb_sysopen - C:/Program Files (x86)/Ruby22/bin/sass.bat

Any ideas what could be causing this?



via Chebli Mohamed

A better way to do conditional active record statements?

I'm trying to figure out a better way to have one query here. I want to be able to send something to last where statement a wildcard so I can select all vendors. Right now if i don't include that line it doesn't filter by vendor so I essentially get all the purchase requests.

Any thoughts of a cleaner way to do these sorts of queries?

  if @vendor == "0" #checks for vendor
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
  else
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
                          .where("purchaseorder.VendorRef_ListID = ?", @vendor)
  end



via Chebli Mohamed

Unexpected label while trying to iterate over a ruby hash

I am in the process of trying to iterate over a ruby hash. I'll have to admit that my knowledge of ruby is very poor and i am in the process of trying to correct that, and so please bear with me if this is a very elementary question.

I am wondering if the syntax of my hash is off. The reason why it is looking the way that it is is because it is part of a rakefile, and i need to incorporate multiple addresses in this. (which i've never done, i've always only had 1 address to worry about) I know the solution to this is to build the addresses in as a rakefile, and then loop over them.

clinic.build_address.each do | build_address |
                            {
                              (city: "Minneapolis"
                              state: "MN"
                              address1: "316 10th ave"
                              zip: "55414"),
                              (city: "Hudson"
                              state: "WI"
                              address1: "119 Belmont Street"
                              zip: "54016")
                            }

With what I have right now I am getting an unexpected label (it is not liking that I have 'city:minneapolis')

Would anybody be able to take a quick look at what I have with this?



via Chebli Mohamed

How can I make files inaccessible to the user, but accessible to my program?

I am making a small game at the moment, and want it to be possible for users to save their characters, which will likely be stored in a text file. Is there any way to make this text file inaccessible to the user in the windows explorer or whathaveyou, so that save tampering is impossible (or at least harder), but also accessible to my program?



via Chebli Mohamed

I don't know why I can't display an image when I create a product using CarrierWave? I also get an error now when I want to edit my product.

I'm using Rails -v 4.2.1 & ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin14.0]

controllers/products_controller.rb

class ProductsController < ApplicationController
  before_filter :find_product, only: [:edit, :show, :update, :destroy]

  def index
    @products = Product.order("created_at DESC")
  end

  def show
  end

  def new
    @product = Product.new
  end

  def create
   @product = Product.new(product_params)

   if @product.save!
      flash[:success] = "Product created!"
      redirect_to products_path
    else
      flash[:danger] = "Error creating product."
      redirect_to new_product_path
    end
  end

  def edit
  end

  def update
    if @product.update_attributes(product_params)
      flash[:success] = "Product Updated!"
      redirect_to products_path
    else
      redirect_to "edit"
    end
  end

  private

  def product_params
    params.require(:product).permit(:name, :description, :price, :images)
  end

  def find_product
    @product = Product.find(params[:product_id])
  end
end

models/product.rb

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

uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :file

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :thumb do
    process resize_to_fill: [200, 200]
  end 

  version :small_thumb, from_version: :thumb do
    process resize_to_fill: [20, 20]
  end

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end



via Chebli Mohamed

Does ActiveSupport's Object#try method work with Thor::CoreExt::HashWithIndifferentAccess?

I'm working on a Middleman (Ruby) site. There are data objects which are instances of Thor::CoreExt::HashWithIndifferentAccess. However, it seems whenever I call try that I get nil.

I see that Thor::CoreExt::HashWithIndifferentAccess takes advantage of method_missing. Does this break how try works? Is anyone able to replicate this?

UPDATE: Here's a simple example. I'm using Middleman which provides access to data files.

# /data/people.yml
jane:
  name: Jane Doe
  age: 25
john:
  name: John Doe
  age: 25

Then in a template you have access to the data.people method which returns a Thor::CoreExt::HashWithIndifferentAccess instance:

data.people.inspect
 #=> {"jane"=>{"name"=>"Jane Doe", "age"=>25},"john"=>{"name"=>"John Doe", "age"=>25}}

data.people.class
 #=> Thor::CoreExt::HashWithIndifferentAccess

Now when I call try on anything I get nil:

data.people.jane
 #=> {"name"=>"Jane Doe", "age"=>25}

data.people.try('jane')
 #=> nil

data.people.try(:jane)
 #=> nil

data.people.try(:something_that_does_not_exist)
 #=> nil

data.people.jane.try(:name)
 #=> nil



via Chebli Mohamed

"Watir::Exception::NoMatchingWindowFoundException: browser window was closed" error when using IE with Page-Object

I'm running tests in Ruby Mine 2.7.1 using Page-Object + Rspec.

Environment: Windows 7 x64, Ruby 1.9.3 p551, IE 11.

Gems: watir, rspec, bundler, page-object

When i run tests in Chrome or Firefox everything is ok.

But when i try to run them in IE, the IE window with correct page gets opened and after that i get an error specified in Subject: "Watir::Exception::NoMatchingWindowFoundException: browser window was closed"

The point is that the browser is actually open at that moment and shows a correct page. (See the screencast showing what happens: http://ift.tt/1hhIBzU)

Test gets finished with an error and the config.after do section doesn't get executed because the browser window remains opened.

That error happens when the following code is executed:

before(:each) do

visit <ClassName>

end

Seems like the IEDriverServer loses connection with IE right after the page is opened.

The most confusing this is that in very rare cases, everything is working good, and in even more rare cases everything is working with significant slowdowns with timeout error at the end.

sleep <n> delays don't help.

I tried different versions of selenium-webdriver gem (it is required by watir gem), different versions of IEDriverServer for both x86 and x64 platforms - result is the same.

What do i do to set IEDriverServer not to lose the IE browser?



via Chebli Mohamed

How to implement sudo su in Ruby script?

I have sudo access to oracle user being non_root user (say guest_admin user). I need to login as oracle user to run some steps but my ruby script is failing at the very first step i.e., sudoing as oracle. Below is the piece of code.

require "java"
require "highline/import"
require "rubygems"
require 'rvm/capistrano'

curr =  File.expand_path(File.dirname(__FILE__))
$LOAD_PATH << curr  unless $LOAD_PATH.include? curr

system "sudo su - oracle"

I am getting the following error:

ruby test.rb

$rvm_path (/usr/local/rvm/scripts/rvm) does not exist.
/usr/local/rvm/scripts/rvm: line 171: __rvm_teardown: command not found
stty: standard input: Invalid argument
stty: standard input: Invalid argument

Can somebody help me fixing this? It's a show-stopper for me right now.

I tried to move require 'rvm/capistrano' at the end of the file but that dint help much.

Thanks.



via Chebli Mohamed

Check how many parameters block being passed has, and then invoke yield with different parameters

I want to know if something like this is possible, as hash.each does two different things based on arguments passed to block

{ "a"=>3, "b"=>2}.each {|k| puts k}

{ "a"=>3, "b"=>2}.each {|k,v| puts k}

Both output different things, and not just what's below..

a
b
..
a
b

i get this

a
3
b
2
..
a
b

So i want to know if there is a way to get my function to do something custom depending on the number of arguments of block being passed to it.

like this

def my_method do
   if yield.args==2
     yield("hi","bro")
   else 
     yield("what's up")
   end
end

my_method {|a,b| puts a; puts b;} //"hi" "bro"

my_method {|a| puts a; } //"whats up"



via Chebli Mohamed

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?



via Chebli Mohamed

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?



via Chebli Mohamed

why does the array elements change after block?

I am trying to solve this problem

Given a sentence containing multiple words, find the frequency of a given word in that sentence.

Construct a method named 'find_frequency' which accepts two arguments 'sentence' and 'word', both of which are String objects.

Example: The method, given 'Ruby is The best language in the World' and 'the', should return 2 (comparison should be case-insensitive).

Hint: You can use the method Array#count to count the frequency of any element in the given array.

Since the comparison should be case-insensitive. I use these code to help:

word = "the"
word_set = []
word.size.times do |i|
  word[i] = word[i].upcase
  word_set << word
  word[i] = word[i].downcase
end

Inside the block every time after upcase method the word does change and does add to the word_set, however when the block finish the word_set just contain the the the What is the problem?



via Chebli Mohamed

Travis CI command is not available from console

I've installed the travis gem

gem install travis

Installed successful, but travis login is not available from console (Ubuntu):

travis login
-bash: /usr/bin/travis: No such file or directory



via Chebli Mohamed

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,



via Chebli Mohamed

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.



via Chebli Mohamed

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 ?



via Chebli Mohamed

Finding a definition of a method in a big github repository

I'd like to know the definition of method from a huge github repository (say from example i want to see the definition of super method in this github repository).

Are there any tools to do it quickly?



via Chebli Mohamed

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



via Chebli Mohamed

define_method with predefined keyword arguments

I want to define a method that takes keyword arguments. I would like it to raise when keyword arguments are not provided, and I can code this myself - but ideally I would like to let Ruby do that for me. Also I would like to be able to inspect the freshly defined method using Method#parameters. If I use a shorthand double-splat (like **kwargs) the actual structure I expect is not visible to parameters.

I can of course do this:

define_method(:foo) do | foo:, bar: |
  # ...
end

which achieves the desired result:

method(:foo).parameters
# => [[:keyreq, :foo], [:keyreq, :bar]]

but I cannot pass those arguments programmatically, they have to be literally placed in the code. Is there a way I could bypass this?



via Chebli Mohamed

Push websocket notification with Faye from Observer in Rails 4

I'm trying to build a simple websocket notification system using rails observers gem and faye. The problem is that I can't publish with faye from the observer.

First I created the observer:

class ScoreObserver < ActiveRecord::Observer

     def after_save(score)
       @notification = Notification.new(user_id: '2', content: '¡rororscoreeeeeeeeeeeeee!')
       if @notification.save
          client = Faye::Client.new('http://localhost:9292/faye')
          client.publish("/messages/new", {
            'title' => 'testitle',
            'content' => 'testcontent'
            })
       end      
     end

end

As you can see it 'observes' the scores model and insert a record in the notifications table. After that I want it to push a notification with faye using pubilsh.

Then in the client side I run the subscribe script

$(function() {
  var faye = new Faye.Client('http://localhost:9292/faye');
  faye.subscribe("/messages/new", function(data) {
    eval(data);
    alert('it works')
  });
});

And it doesn't work. The observer is aware of the action and makes the record save correctly but the client doesn't receive any push from the websocket.

I've tested the subscription with a simple broadcast and it works so it seems that is the observer part which is failling. Websockets are up and listening

Do you have any clue of what could be wrong ?

I was looking for an alternative just in case this approach is wrong, and I thought about render a script from the observer and broadcast/publish from a .js file, since all the tuts do it from a script. But I'm having some trouble with this approach too, I can't render a script from the observer in respond_to since the model extends from Observer and not from Base and doesn't have the method.

Thanks



via Chebli Mohamed

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 an user logs in I want to display all files, but files downloaded by current user should be displayed last. The file table has about 500 records so I need simple and fast method to achieve this. How to do this?

The technologies I am using

  • Rails 4.2.1
  • Ruby 2.2.2
  • PostgreSQL


via Chebli Mohamed

Convert Jira's time tracking field format to hours

I am using JIRA api to extract timespent by users on issues. The time spent is in the format:

"12w 1d 2h 5m" or "12h" or "12m" etc

The API isn't exporting the number of hours. Is there a quick (requires no effort on my part) way to convert this to hours (or seconds). I suppose this is some sort of a standard format, is there a name for it? I know how to do this myself, just don't want to reinvent the wheel



via Chebli Mohamed

how can I convert a string to JSON in Ruby

I have read the data online but it is in a string format. I've also researched online but the few examples I checked returned string format too. How can i make it so that it returns a JSON object.

assuming the result of reading the data was

text = '{"one":1,"two":2}'

then i used:

data = JSON.parse(text).to_json 

but when i do

puts data.class

the result is still a string



via Chebli Mohamed

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.



via Chebli Mohamed