mardi 4 août 2015

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.

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?

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

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.

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.

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.

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?

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.

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!

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!

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... ;(

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.

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.

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.

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?

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"

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]])

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!

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?

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?

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

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?

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?

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

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

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

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.

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"

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?

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?

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

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 ?

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?

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

How to create a nested class when subclassing

I'm wanting to create a pair of classes. The second of the pair sub-classes the first, is nested within the first, and only has the addition of being an Enumerator. Like so:

MyClass                          # this is the parent class
MyClass::Enumerator              # it has an Enumerator which sub-classes MyClass

Further to this, when sub-classing MyClass, the subclass should get its own iterator which is also nested within it. Like so:

MySubClass = Class.new(MyClass)  # This class sub-classes MyClass
MySubClass::Enumerator           # It has an Enumerator which sub-classes MySubClass

I've actually created the code and it works, but I'm wondering if there is a better way or an existing design pattern to achieve this. The code I've written to make this work is the following:

module EnumerableCompanionClass
  extend ActiveSupport::Concern

  # this ensures the parent class gets it's companion class
  included { create_enumerable_class }

  module ClassMethods
    # this ensures an descendants get their companion class
    def inherited(sub)
      # need to make sure this doesn't get called for the companion class.  
      # at this point it's still an anonymous class
      # this is to stop infinite recursion
      unless sub.name.blank? || sub < Enumerable
        sub.create_enumerable_class
      end
    end

    def create_enumerable_class
      # only create the companion class once
      @enumerable_class ||=
        # create the companion class as a subclass of the current class
        # but only if self is a class (not a module) and is not the companion class
        if self.is_a?(Class) && !(self < Enumerable)
          enumerable_class = Class.new(self) do
              include ::Enumerable
              # my custom each method
              def each(&block); end
            end
          # define a constant for the companion class
          const_set('Enumerable', enumerable_class)
        end
    end
  end
end

And this is the code to check that it works as expected:

class A
  include EnumerableCompanionClass
  def test1; 'this should work!'; end
end

A::Enumerable.parent == A   # true
A::Enumerable.new.test1     # 'this should work!'

class B < A
  def test2; 'this should also work'; end
end

B::Enumerable.parent == B   # true
B::Enumerable.new.test1     # 'this should work!'
B::Enumerable.new.test2     # 'this should also work'

class C < B
  def test3; 'this should triple work'; end
end

C::Enumerable.parent == C   # true
C::Enumerable.new.test1     # 'this should work!'
C::Enumerable.new.test2     # 'this should also work'
C::Enumerable.new.test3     # 'this should triple work'

So as you can see from the output, it all works as expected.

But it's messy and not very intuitive. For starters, the included method is only there for the parent. Likewise, the inherited method is only there for the sub-classes. The checks for anonymous classes and unnamed classes are there to prevent infinite recursion (we don't want the Enumerator classes to have it's own Enumerator).

I'm happy that it works but I'm sure there has to be a better way. I've tried other methods and this is the only one that I've gotten to work correctly so far.

Does any one know the canonical way to achieve this, or a better design pattern?

Thanks in advance!

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

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?

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

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

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.

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:3000/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

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

Ruby DBI fetch can't handle all-zero dates in MySQL

I'm trying to access our database with some fairly simple CGI/Ruby and DBI:

#!/usr/bin/ruby -w

require "dbi"
dbh = DBI.connect("dbi:Mysql:my:mydb", "XXXX", "XXXX")

...

query = "select ETA from mydb.mytable where ID = #{someval}"
rows = dbh.execute(query)
while row = rows.fetch() do
    # Do some stuff
    ...
end

That works fine most of the time, but I hit a record which broke it with the error:

/usr/lib/ruby/vendor_ruby/dbd/Mysql.rb:120:in `parse': invalid date (ArgumentError)
        from /usr/lib/ruby/vendor_ruby/dbd/Mysql.rb:120:in `parse'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:66:in `block in convert_types'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:65:in `each'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:65:in `each_with_index'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:65:in `convert_types'
        from /usr/lib/ruby/vendor_ruby/dbi/row.rb:75:in `set_values'
        from /usr/lib/ruby/vendor_ruby/dbi/handles/statement.rb:226:in `fetch'
        from /usr/lib/cgi-bin/test:39:in `block in <main>'
        from /usr/lib/cgi-bin/test:36:in `each'
        from /usr/lib/cgi-bin/test:36:in `<main>'

After a bit of detective work I found that it had a date of 0000-00-00 which fetch() doesn't like. Undefined dates are OK, and DBI in Perl can handle all zero dates, it's just DBI in Ruby.

I can fix the database, and I'll try to get the app which wrote the value to the database fixed too, but I think that my Ruby should be resilient to such things. Is there a way to work around this, maybe using rescue somehow?

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

How do I embed icons into text within Squib only on certain cards?

Here is my current deck.rb file:

require 'squib'
require 'game_icons'

Squib::Deck.new(cards: 4, layout: %w(hand.yml layout.yml), width: 825, height: 1425) do
  background color: '#FFFFFF'
  rect x: 0, y: 0, width: 825, height: 1425, x_radius: 38, y_radius: 38
  data = csv file: 'country.csv'
  png file: data['Art'], layout: 'Art'
  png file: 'textbox.png', x: 50, y: 890
  png file: 'titlebox.png', x: 65, y: 30

text(str: data['Ability'], x: 100, y: 900) do |embed|
    embed.svg key: ':tribute:', file: 'tributesmall.svg'
end

  %w(Title Ability Quote Type Subtype).each do |key|
    text str: data[key], layout: key, markup: true
  end

  %w(Tribute Power Dominion).each do |key|
    svg file: "#{key.downcase}.svg", layout: "#{key}Icon"
    text str: data[key], layout: key
  end

  save_png prefix: 'country_'
end

This puts the Ability column of my .csv onto every single card. However, it doesn't replace any text with icons. If I switch the relevant block to this:

text(str: 'Gain 1 :tribute:', x: 100, y: 900) do |embed|
    embed.svg key: ':tribute:', file: 'tributesmall.svg'
end

This now puts "Gain 1 [my tribute icon]" onto every single card.

Here's exactly what I want to do: Whenever one of my cards has within the Ability column of my .csv the text "Gains 1 tribute", the output is "Gains 1 [my tribute icon]" within the text box of the card, formatted so that it's part of the regular Ability text. Is this possible?

Thanks!

Comparing large powers in Ruby using Mod 10

I am trying to write a function that compares whether one number x1 to the power of another number x2 is greater than another number y1 to another number y2 power.

For example, suppose we have a pair of numbers for x.

x = [2,10]

and another pair y

y = [3,9]

In this case y1 ** y2 is greater than x1 ** x2.

However, sometimes there are really large, scary numbers. Like so

x = [935243113, 987702643]
y = [50894069, 704259526]

To calculate this, I tried using the mod 10 algorithm

(x[0] ** x[1]) % 10 > (y[0] ** y[1]) % 10 

However, apparently this algorithm doesn't work. Is there a more efficient algorithm for this.