FAQ Database Discussion Community


For loop with flexible stop variable

ruby
I need to write a loop for x in (1..y) where the y variable can be changed somehow. How can I do that? For example: for x in (1..y/x) But it does not work. ...

Couldn't find User with 'id'=show

ruby-on-rails,ruby,devise
a Rails/Devise Question for you today. I'm working on user profiles for a site and I am hitting this error ActiveRecord::RecordNotFound at /users/show Couldn't find User with 'id'=show Not sure exactly what's happening as I haven't really run into anything like this before. Here are some necessary files to take...

Making Serverspec mutlit-host tests continue even on a test failure

ruby,serverspec
I've built some serverspec code to run a group of tests on multiple hosts. The trouble is that the testing stops at the current host when any test fails. I want it to continue to all hosts even if a test fails. Relevant part of rakefile: namespace :spec do task...

How to handle backslash “\” escape characters in q string and heredocument

ruby
Ruby Newbie here. I do not understand why Ruby looks inside %q and escapes the \. I am using Ruby to generate Latex code. I need to generate \\\hline which is used in Latex for table making. I found \\\hline as input generated \hline even though the string was inside...

Does rails have an opposite of `parameterize` for strings?

ruby-on-rails,ruby
I used parameterize method. I want to de-parameterize it. Is there a method to do the opposite of parameterize?

Installing GitLab CI Runner on Raspberry Pi 2 (Raspbian)

ruby,gitlab,raspberry-pi2
I want to install the GitLab Runner for CI on my RPI 2 machine running Raspbian. There is no armhf package available or mentioned on the official page: https://gitlab.com/gitlab-org/omnibus-gitlab-runner/blob/master/doc/install/README.md and I could not find one on the net. I've tried building it from source but it failed to make ruby...

edit first line of multiple files in place with a ruby one-liner

ruby
I can edit multiple files in place using the -p -i -e command line options: ruby -pi -e 'sub(/a/,"b")' file* How can I edit only the first line of each file? This works for one file only: ruby -pi -e 'sub(/^/,"New line goes at top\n") if $. == 1' file1...

In Ruby, how can I convert this string format to a hash

ruby
The string format is like this "a.b.c = 1" "a.b.d = 2" => its hash will be => {'a'=> {'b' => {'c'=>1, 'd'=>2 } } } It gets tricky with arrays "a.e[0].f = 1" "a.e[0].g = 2" "a.e[1].h = 3" => its hash will be => {'a' => {'e' =>...

Opal.rb anonymous function in native object

ruby,opalrb
Is it possible to somehow achieve methods/lambda assigned in Hash to compile to native functions in native object? for example let x = {foo: "foo", bar: ->{"bar"}} I need that x to be compiled like such native object: pseudo x.to_n => Object {foo: 'bar', bar: function(){return "bar";}} OK THAT WORKS...

Ruby gsub group parameters do not work when preceded by escaped slashes

ruby,regex
I am trying to perform a trivial substitution, that in any other language I have come across, work as per the documentation. However, my substitution fails for some reason. The documentation examples list: "hello".gsub(/[aeiou]/, '*') #=> "h*ll*" "hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>" "hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101...

Ruby each loop based on array

ruby,sinatra
I have an array like this: @airports = [ ['Malaysia', 'Alor Setar', 'AOR'], ['Malaysia', 'Bintulu', 'BTU'], ['Malaysia', 'Ipoh', 'IPH'], ['Malaysia', 'Johor Bahru', 'JHB'], ['Indonesia', 'Kuching', 'KCH'], ['Indonesia', 'Labuan', 'LBU'], ['Indonesia', 'Langkawi', 'LGK'], ['Indonesia', 'Miri', 'MYY'], ['Indonesia', 'Penang', 'PEN'], ] then in my view: <select name="from" class="form-control select2"> <% @airports.each do...

Elasticsearch advanced search

ruby-on-rails,ruby,search
I find Elasticsearch gem and want to use it. For example I have: Method in app/controller/search_controller.rb: def search if params[:q].nil? @articles = [] else @articles = Article.search params[:q] end end View at app/views/search/search.html.erb: <h1>Articles Search</h1> <%= form_for search_path, method: :get do |f| %> <p> <%= f.label "Search for" %> <%=...

No Method When Importing to Rails via CSV

ruby-on-rails,ruby
I'm importing into my Rails App via CSV. The import worked until I tried to create a new contact using one of the columns on my CSV. Here's the code that imports the data: row = Hash[[header, spreadsheet.row(i)].transpose] hotel = find_by_id(row["id"]) || new hotel.attributes = row.to_hash.select { |k,v| allowed_attributes.include? k...

RoR: removing sensitive field from response

ruby-on-rails,ruby,rails-activerecord
Is there any way to remove sensitive fields from the result set produced by the default ActiveRecord 'all', 'where', 'find', etc? In a small project that I'm using to learn ruby I've a reference to User in every object, but for security reasons I don't want to expose the user's...

Prevent upvote model from being called for every comment

ruby-on-rails,ruby,database,performance,model
I have three models: User, Comment and Upvote. User-to-Comment has a one-to-many relation, Comment-to-Upvote has a one-to-many relation and User-to-Upvote has a one-to-many relation. I want to do something similar to the upvoting done on Stackoverflow. So when you upvote/downvote the arrow will highlight and remain highlighted even if you...

RSpec test for rake task

ruby-on-rails,ruby,rspec,rake-task
I have created a custom rake task that deletes all items that are >= 7 days old. I am trying to write a RSpec test for this new task but it seems like my task isn't really running in the test. I have tested the task manually and it works...

How do I change the Rails timezone on Windows?

ruby-on-rails,ruby
I'm unable to change the timezone on Windows. It always gives my local time zone. It works on Heroku. application.rb # config.time_zone = 'Central Time (US & Canada)' Console >rails runner "p Time.zone.name;p Time.now" DL is deprecated, please use Fiddle "UTC" 2015-06-16 14:30:05 -0400 Change application.rb config.time_zone = 'UTC' Console...

How to add link_to under Div on ActiveAdmin's show page | Rails 4

ruby-on-rails,ruby,activeadmin,show
I have implemented one panel of Active Admin's show page. In this panel I am showing list of data by loop. Here is what I did: show do default_main_content panel "Best #{trip_type.camelize} (Live)" do live_datas1.each do |live| div do live["outbound_date"].strftime('%A')+ ", " + live["outbound_date"].strftime('%Y-%m-%d') + " To " + live["inbound_date"].strftime('%A')...

Having trouble calling a Proc within a Method within a Class

ruby,proc
I am struggling to debug my issue; I am trying to use a Proc within a method, all inside a class. When I don't type in the "class" details, my program compiles fine; when I specify the class name, however, I get a variety of different errors. Note: I posted...

How to use Rails #update_attribute with array field?

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord
Each question has an array of tags. schema.rb: create_table "questions", force: true do |t| t.text "tags", default: [], array: true How to atomically append to tags? How to prevent dups within the array? I tried question.update_attribute tags: tags << :ruby, but this doesn't work. Rails 4.17 and Postgres. EDIT: This...

How to get return value from a forked / spawned process in Ruby?

ruby,process,output,fork,spawn
My simple test program: pid = Process.spawn("sleep 10;date") How can I place the output (eg stdout) of the "date" command in a variable when it is available? I don't want to use a file for the data exchange....

Ruby on Rails posting to an API using javascript via a proxy

javascript,ruby-on-rails,ruby,xml,api
I'm very new to Ruby on Rails and I'm hoping this will be a quick fix. I have a very simple form (firstname, surname, email) that needs to post XML to an API on another domain. Everything on our site is clientside javascript so I would like to post to...

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter
I have a model named Tweet. The columns of the Tweet model are: -id -content -user_id -picture -group -original_tweet_id Every tweet can have one or multiple retweets. The relation happens with the help of original_tweet_id. All the tweets have original_tweet_id nil , whilst the retweets contain the id of the...

Grab host app active record objects when engine and host app have same model names

ruby-on-rails,ruby
I have a host app unicorn with the model Article. I also have a mountable engine hooked into the host app called blorgh. It also has a model: Article. It is namespaced, so the table name for the engine's Article is actually blorgh_articles. While inside the engine I want to...

Ruby- get a xml node value

ruby,xml
can someone help me in extracting the node value for the element "Name". Type 1: I am able to extract the "name" value for the below xml by using the below code <Element> <Details> <ID>20367</ID> <Name>Ram</Name> <Name>Sam</Name> </Details> </Element> doc = Nokogiri::XML(response.body) values = doc.xpath('//Name').map{ |node| node.text}.join ',' puts values...

Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku
My app is working fine locally and my push to Heroku was successful. But, when I run heroku run rake db:migrate, I get the following error: NameError: uninitialized constant AddWeightToExercises Here is the failed migration: class AddWeightToExercise < ActiveRecord::Migration def change add_column :exercises, :weight, :float end end edit: Thanks for...

Combining items into interval bins by timestamps

javascript,ruby-on-rails,ruby
This is basically what I need to do but I'm not working with a table so I need to do it in Ruby/Rails or even Javascript. The data is returned from an external call that's a bit slow so I'm trying to format the data as quickly as possible. There...

Ruby if else statement one line not working

ruby-on-rails,ruby,ruby-on-rails-4
I have the following properly working line in a view that adds a class depending on the current_page of the user: <li class="hvr-bottom <%= 'active' if current_page?(root_path) %>"> <%= link_to "Home", root_path %> </li> Now I would also like to add a different class for the else situation, and I...

How to stub a class method using rspec/rspec-mocks

ruby,rspec,mocking
I am using rspec-mock for test-driven-development. I am starting implementing a single class and mocking/stubbing the other classes using rspec-mock. Mocking objects of classes yet to be implemented works well. However when I try to mock a class method of a class that does not exist yet, I haven't been...

Get X days out of an Array

ruby,ruby-on-rails-4
I have an array filled with Datetime objects: [Mon, 22 Jun 2015, Tue, 23 Jun 2015, Wed, 24 Jun 2015, Thu, 25 Jun 2015, Fri, 26 Jun 2015, Sat, 27 Jun 2015, Sun, 28 Jun 2015] I know how to select what I want from the array ex: week.select{|x|x.monday? ||...

Call method to generate arguments in ruby works in 1.8.7 but not 1.9.3

ruby-on-rails,ruby,ruby-1.9.3
This is something that I had working in ruby 1.8.7, but no longer works in 1.9.3, and I am not sure what changes make this fail. Previously, I had something like this myFunction(submitArgs()) where submitArgs was a helper method that could be called with some options def submitArgs(args={}) #Some logic/manipulations...

is there an equivalent of the ruby any method in javascript?

javascript,arrays,ruby,iteration
Is there an equivalent of ruby's any method for arrays but in javascript? I'm looking for something like this: arr = ['foo','bar','fizz', 'buzz'] arr.any? { |w| w.include? 'z' } #=> true I can get a similar effect with javascript's forEach method but it requires iterating through the entire array rather...

Seach by class in Nokogiri nodeset

ruby,xpath,nokogiri
I got the name of a CSS class from a Nokogiri node. Now I want to find all the nodes that also have the same class attached. I don't know which HTML tag the element that I'm looking for has, and how deep it is. All i know is what...

Heroku RAM not increasing with upgraded dynos

ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku
I have a massive function i have been calling manually through the heroku rails console. I have been receiving the error rapid fire in my logs: 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Process running mem=575M(112.4%) 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Error R14 (Memory quota exceeded) A 1X dyno is suppose to have 512 MB of RAM. I...

User path with username

ruby-on-rails,ruby,path,user,friendly-id
To show User's profile I used their id. In controller: @user = User.find(params[:id]) In routes: get ':id' => 'users#show' But now I try new way with username: get ':username' => 'users#show' #route @user = User.find_by(username: params[:username]) #controller And when I go to user's profile with /username I see error: undefined...

How to pivot array into another array in Ruby

arrays,ruby,csv
I have a multidimensional array like this one : myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] I would like to end up with CSV output like this. State,Snow,Rain,Hail Alaska,4,3,nil Alabama,2,nil,1 I know that to get this outputted to CSV the way I want it I have to have output array like this: outputArray =[["State","Snow","Rain","Hail"],["Alaska",4,3,nil],["Alabama",2,nil,1]]...

Undefined local variable post

ruby-on-rails,ruby,variables,undefined,local
I write this code: <% @user.posts.each do |post| %> <%= render 'post', locals: { post: post, user: @user} %> <% end %> Then in _post.htm.erb I write follow code: <div class="post-title"> <img src="<%= @user.avatar.url%>" class="img-rounded post-image"> <h4 id="post-name"><%= @user.first_name + ' ' [email protected]_name %> </h4> <div id="post-date"><%= post.created_at.strftime('%d %b -...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations
An Organization model has a 1:many association with a User model. I have the following validation in my User model file: belongs_to :organization validates_presence_of :organization_id, :unless => 'usertype==1' If usertype is 1, it means the user will have no organization associated to it. For a different usertype the presence of...

Ruby boolean logic: some amount of variables are true

ruby
Let say I have 3 variables: a, b, c. How can I check that just zero or one of them is true?...

Rails less url path change

ruby-on-rails,ruby,url,path,less
Developing a Rails application with the less-rails gem I found something unusual : // app/assets/common/css/desktop/typo.less @font-face{ font-family:'SomeFont'; src:url("fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); // ... } The requested font is app/assets/common/css/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot This font is compiled with less and the results is : @font-face { font-family: 'SomeFont'; src: url("desktop/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } Do you know why is...

Rspec: Factory Girl & Complex Associations

ruby-on-rails,ruby,rspec,tdd,factory-girl
I am trying to test a helper method that would return the amount of Subscribers a Campaign is targeting. Being fairly new to TDD, I am having a hard time wrapping my head around how to write this one since the associations are quite complex. A Campaign "targets" by whether...

Allowing some enabled and disabled option on collection_select

ruby-on-rails,ruby
I am trying to populate a dropdown box on a view that has all the states. This works just fine: <%= f.collection_select :state_id, @states, :id, :name %> Now, I need to make the following: Some states are going to be disabled for choosing, but they still have to appear on...

Batch file to open multiple instances of cmd and run Ruby script in each instance

ruby,windows,batch-file,cmd,watir-webdriver
I'm trying to open multiple instances of cmd up which each run a ruby script at the same time. For background into the scripts, each of these ruby scripts run watir-webdriver and spawn new browser instances. All of this should happen instantaneously. Here's what I've tried: start cmd /k cd...

Ruby Dir.glob mystery: Where are the FNM_xxx flags described?

ruby
Note: This has already been posted on Ruby Forum some weeks ago. I'm crossposting it here, because I didn't get any response so far Dir.glob provides an optional parameter, usually referred as 'flags'. Where can I find a documentation about what flags are possible? The Ruby 2.0 docs just say...

Saying there are 0 arguments when I have 2? Trying to open a CSV file to write into

ruby,file,csv,dir
I'm trying to read from a CSV file and codify people into groups using an equation. I append the name of their group they fall into to the end of the array that their row creates. Then I write it to a new file so I don't overwrite the original...

Iterating over EncryptedDataBagItem in Chef Recipe

ruby,json,chef,devops
I would like to decrypt a chef data bag item (named passwords) and store all of its attributes in a temporary JSON file which is read (and then deleted) by a node.js app. Is there a way to iterate over attributes of a data bag ITEM and get their values?...

On rendering from controller, current_page method does not seem to work

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller
I have a navigation bar included in application.html.erb. Because for some pages, such as the signup page, I need to place additional code inside the navigation bar, I have excluded those pages for showing the navigation bar through application.html.erb and instead included it in their respective view pages. See code...

Same enum values for multiple columns

ruby-on-rails,ruby,enums
I need to do something like this: class PlanetEdge < ActiveRecord::Base enum :first_planet [ :earth, :mars, :jupiter] enum :second_planet [ :earth, :mars, :jupiter] end Where my table is a table of edges but each vertex is an integer. However, it seems the abvove is not possible in rails. What might...

How to map browser dialog using capybara/selenium

ruby,selenium,capybara
What is the best way to handle browser dialogs (with ok/cancel buttons) using capybara/selenium? The way I found easiest is by running the following: dialog = page.driver.browser.switch_to.alert dialog.accept Any thoughts for a better approach? Whoever downed this post please give a valid reason... it's not helpful to down vote with...

Split an array into slices, with groupings

arrays,ruby,enumerable
I've got some Ruby code here, that works, but I'm certain I'm not doing it as efficiently as I can. I have an Array of Objects, along this line: [ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york"...

Ruby - at least one item in array ALSO in line

ruby,regex
Given this array: ["/Item A/", "/Item B/"] and a line: Here's a line of text that includes /Item B/ what's a good, idiomatic, Ruby way of checking if the line includes at least one phrase from the array?...

Rails add hash into existing hash

ruby,ruby-on-rails-4
I would like to do smth like: a = Hash.new a = {:profile => @user} a[:profile][:contacts] = Hash.new a[:profile][:contacts] = @user.contacts.all but I am getting the error can't write unknown attribute `contacts'. @user is the result of a select from our database. I need to create a hash with this...

Rails basic auth not working properly

ruby-on-rails,ruby,authentication
I am building a small API that uses basic authentication. What I have done, is that a user can generate a username and password, that could be used to authenticate to the API. However I have discovered that it is not working 100% as intended. It appears that a request...

a repeated permutation with limitations

arrays,ruby,permutation
I am trying to generate all possible combinations of certain values in an array of 15 which add up to 50. $a = [3, 4, 1, 2, 5] print $a.repeated_permutation(15).to_a In this case, [2,2,2,2,4,4,4,4,4,4,4,4,4,3,3] [2,2,2,4,2,4,4,4,4,4,4,4,4,3,3] [2,2,4,2,2,4,4,4,4,4,4,4,4,3,3] are all possible answers. After some investigation I realize the code to do this...

regex to pull in number with decimal or comma

ruby,regex
This is my line of code: col_value = line_item[column].scan(/\d+./).join().to_i When I enter 30,000 into the textfield, col_value is 30. I want it to bring in any number: 30,000 30.5 30.55 30000 Any of these are valid... Is there a problem with the scan and or join which would cause it...

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

ruby-on-rails,ruby,rack,multipart
Rack::Utils.multipart_part_limit is set to 128 by default. What purpose does the value have and what effect does it have within the Rails system?...

Ruby API Call Page Issue

ruby-on-rails,ruby,json,api,httparty
This might be a basic issue but very common so it might be helpful to other people in the future. I use HTTParty to make a get request to an API, which returns some information, something like this: { datapath: "blah-blah.blah.blah", success: true, info: { row_limit: 500, total_results: 2700, total_pages:...

When to use (:method) or (&:method)

ruby
Why does: respond_to? in: class Wolf def howl; end end Wolf.new.respond_to?(:howl) # => true not require & while map in: ["1", "2", "3"].map(&:to_i) # => [1, 2, 3] does? Also, are there any technical names for this?...

how to define extra method for rails form text_field

ruby-on-rails,ruby
After removing dimensions from my table, my scaffolded view hit this error: undefined method 'dimensions' for this code: <div class="field"> <%= f.label :dimensions %><br> <%= f.text_field :dimensions %> </div> I want to keep this dimention field in the form and in the controller I want to split this string into...

Using attr_accessor from inside class? [duplicate]

ruby,attr-accessor
This question already has an answer here: Why do Ruby setters need “self.” qualification within the class? 3 answers I'm trying to use an attr_accessor from inside the class where it is defined, to no avail. Why does this not work? I would expect the following to output "new"...

String#scan not capturing all occurences

ruby,regex
I'm facing a very strange behaviour with ruby String#scan method return. I have this code below and I can't find out why "scan" doesn't return 2 elements. str = "10011011001" regexp = "0110" p str.scan(/(#{regexp})/) ==> [["0110"]] String "str" clearly contains 2 occurences of pattern "0110". I want to fetch...

Get the actual value of a boolean attribute

ruby,page-object-gem,rspec3,rspec-expectations
I have the span: <span disabled="disabled">Edit Member</span> When I try to get the value of the disabled attribute: page.in_iframe(:id => 'MembersAreaFrame') do |frame| expect(page.span_element(:xpath => "//span[text()='Edit Member']", :frame => frame).attribute('disabled')).to eq("disabled") end I get: expected: "disabled" got: "true" How do I get the value of specified attribute instead of a...

Loop until i get correct user

ruby,redis
I have users stored in Redis and want to be able to call only certain subsets from a set, if i don't get the correct user back i want to put it back in the set and then try again until i get one of the desired users @redis =...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many
I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

How could I padding spaces to a fix length

ruby
I need all strings' length with 5 Original [477, 4770,] Expected ["477 ", "4770 "] How could I do it with Ruby ?...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord
In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example: user = User.first # Assuming User to be inheriting from ActiveRecord::Base user.name # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4
I am having trouble building a controller concern. I would like the concern to extend the classes available actions. Given I have the controller 'SamplesController' class SamplesController < ApplicationController include Searchable perform_search_on(Sample, handle: [ClothingType, Company, Collection, Color]) end I include the module 'Searchable' module Searchable extend ActiveSupport::Concern module ClassMethods def...

Map with accumulator on an array

ruby,inject
I'm looking to create a method for Enumerable that does map and inject at the same time. For example, calling it map_with_accumulator, [1,2,3,4].map_with_accumulator(:+) # => [1, 3, 6, 10] or for strings ['a','b','c','d'].map_with_accumulator {|acc,el| acc + '_' + el} # => ['a','a_b','a_b_c','a_b_c_d'] I fail to get a solution working. I...

In Ruby how to put multiple lines in one guard clause?

ruby-on-rails,ruby
I have the following line of code : if params[:"available_#{district.id}"] == 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id) delivery_custom_price(district) end Rubocop highlight it and asks me to use a guard clause for it. How can I do it? EDIT : Rubocop highlighted the first line and gave this message Use a guard...

Get value from string representing local variable [duplicate]

ruby,local-variables
This question already has an answer here: Is there a 'variable_get' method? If not, how can I create my own? 2 answers I have a local variable name as a string, and need to get its value. variable = 22 "variable".to_variable? How can I get the value 22 form...

Switch between windows with frames

ruby,capybara
I have main window with frames and a popup where I do some operations: within_frame("MainFrame") do find("btnNewItem").click #opens popup window end within_window(windows.last) do within_frame("frmFrame2"){ some_operations find("btnOK").click #closes a popup } end within_window(switch_to_window(windows.first)) do within_frame("MainFrame") do find("btnDeleteItem").click #deletes item accept_popup_dialog end end But when operations are done in popup window and...

How to flatten a structure of embedded Set and Hash

ruby,recursion
I would like to convert an embedding structure into a flat one. An embedding structure is a set of 0 or more objects, such as: a string or a hash having some string as key and some other embedding structure as value. A flat structure is a set of arrays...

How do I pass a hash from commandline?

ruby
I have a ruby script that has a hash. Example: animal_sound = { 'dog' => 'bark', 'cat' => 'meow' } I want to add 'snake' => 'hiss' Example: myscript.rb --addsound "'snake' => 'hiss'" Then in my script have it add it to animal_sound. Example: animal_sound.merge! 'snake' => 'hiss' => {"dog"=>"bark",...

Error when trying to install app with mysql2 gem

mysql,ruby-on-rails,ruby,ruby-on-rails-4
Im trying to install an open source rails 3.2.21 application that uses the mysql2 gem, but when i try and run the bundle commant I get the following error: Fetching: mysql2-0.3.18.gem (100%) Building native extensions. This could take a while... p ERROR: Error installing mysql2: ERROR: Failed to build gem...

Rails - link_to path based on object's name + refactoring multiple custom actions

ruby-on-rails,ruby,refactoring
I'm looking to simplify the link_to path based on thr object's name and also am looking into refactoring multiple custom actions. I've managed to get this working below. <% ServiceMenu.all.each do |menu| %> <tr class=" <%= cycle('odd', 'even') %>"> <td><%= link_to menu.name, ("tech/""#{menu.name.parameterize}") %></td> </tr> <% end %> I feel...

Combine logic of boolean value & integer in one activerecord model

ruby-on-rails,ruby,activerecord
Let say I have a model named a Product. Product has a days_lifetime:integer in days (it can expire in 1, 2, 3 et.c. days after initialization). But sometimes Product has unlimited lifetime (it can be stored infinitively long time). So, I need to add another variable like unlimited_lifetime:boolean Now I...

Saving to a database using a Nokogiri (json?) rake task

ruby-on-rails,ruby,json,nokogiri
RoR noob here! I have a rake task doing what I want to do I am just stuck on how to get the results saved to my language table. I want the results from this rake task to populate the values of the language field on my language table. I'm...

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array
seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

Host app and engine with same model name, rendering host app's model from inside engine using host app's partial, rails

ruby-on-rails,ruby,rails-engines
I have a host app unicorn with the model Article. I also have a mountable engine hooked into the host app called blorgh. It also has a model: Article. It is namespaced, so the table name for the engine's Article is actually blorgh_articles. What I am trying to do is...

Controller method: Contact form should render different page depending on where the form is used

ruby-on-rails,ruby,forms,ruby-on-rails-4,controller
I have a contact form on a special page dedicated to this form. The dedicated controller includes: def new @message = Message.new end def create @message = Message.new(message_params) if @message.valid? MessageMailer.new_message(@message).deliver_now flash[:success] = "Thank you!" redirect_to contact_path else render 'new' end end Now I would also like to include this...

rails - NameError (undefined local variable or method while using has_many :through

ruby-on-rails,ruby,ruby-on-rails-4
My rails app gives following error: NameError (undefined local variable or method 'fac_allocs' for #): app/models/room.rb:4:in '' app/models/room.rb:1:in '' app/controllers/rooms_controller.rb:3:in 'index' room.rb file class Room < ActiveRecord::Base has_many :bookings has_many :fac_allocs has_many :facs, :through => fac_allocs end ...

metriks log to file not working

ruby,code-metrics
I wrote a basic program to test the ruby metriks gem require 'metriks' require 'metriks/reporter/logger' @registry = Metriks::Registry.new @logger = Logger.new('/tmp/metrics.log') @reporter = Metriks::Reporter::Logger.new(:logger => @logger) @reporter.start @registry.meter('tasks').mark print "Hello" @registry.meter('tasks').mark @reporter.stop After i execute the program, there is nothing in the log other than it got created. $ cat...

Can't map a range of dates in Ruby/Rails

ruby-on-rails,ruby
I'm trying to map a range of dates and pass them to my view as an array, as follows: from, to = Date.parse("2014-01-01"), Date.yesterday date_range = (from..to) @mapped_dates = date_range.map {|date| date.strftime("%b %e")} I reference them in some JS in my view as follows: dateLabels = <%= raw @mapped_dates.to_json %>;...

Using Ruby Pathname to access relative directory

ruby,path,pathname
Given I have a relative path pointing to a directory how can I use it with Ruby's Pathname or File library to get the directory itself? p = Pathname.new('dir/') p.dirname => . p.directory? => false I have tried './dir/', 'dir/', 'dir'. What I want is p.dirname to return 'dir'. I...

Ruby access words in string

ruby
I don't understand the best method to access a certain word by it's number in a string. I tried using [] to access a word but instead it returns letter. puts s # => I went for a walk puts s[3] # => w ...

Error installing gem twitter on Ubuntu 15.04

ruby-on-rails,ruby,ubuntu,twitter
Am trying to install twitter gem on Ubuntu 15.04 and this error keeps popping up gem install twitter Building native extensions. This could take a while... ERROR: Error installing twitter: ERROR: Failed to build gem native extension. /usr/bin/ruby2.1 extconf.rb mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h extconf failed,...

Keep leading zeroes when converting string to integer

ruby
For no particular reason, I am trying to add a #reverse method to the Integer class: class Integer def reverse self.to_s.reverse.to_i end end puts 1337.reverse # => 7331 puts 1000.reverse # => 1 This works fine except for numbers ending in a 0, as shown when 1000.reverse returns 1 rather...

Rails, default.js is empty, and jquery and jquery_ujs not loaded

jquery,ruby-on-rails,ruby,ruby-on-rails-4,rubygems
I am practicing ruby on rails by using rails guides. In the section 5.13 Deleting Articles they are showing how to create the delete (destroy) functionality. I followed the steps correctly, but the delete confirmation dialogue isn't shown and the articles are not getting deleted. When I checked the chrome...

convert JSON array to Ruby Hash (of hashes)

ruby,json
I'm trying to convert some API response data into a Ruby hash or array so I can more easily work with it. Here's the JSON string being returned by the API: [ { "id": 2, "name": "TestThing", "token": "B2CA27221DB976E48248F26756289B91" }, { "id": 3, "name": "AnotherTestThing", "token": "EF16E5F20B8463E48DBF3BA8F0E1102A" } ] I...

.split and regular expression in Ruby

ruby,regex
I want to split my string by (',') but ignore ',' if they are inside quotes. For example " 2,2,4,'hello', 'world', 'hi, there' " I want to split it so 'hi, there' will not be split into two different array elements in ruby. How can I do that? Probably use...

Get an array including every 14th day from a given date

ruby
In ruby, how can I get every 14th day of the year, going backwards and forwards from a date. So consider I'm billed for 2 weeks of recycling on today, 6-16-2015. How can I get an array of every recycling billing day this year based on that date. ...

What is wrong with this ST_CONTAINS statement PostGIS - Find point in polygon

sql,ruby,gis,postgis
I'm trying the following: Event.where('ST_Contains(?,ST_SetSRID(location, 4326)::geography)', search_polygon::geography) add getting the error *** NoMethodError Exception: undefined method `geography' for but without that (::geography) I get a message telling me to cast, what do I do? HINT: No function matches the given name and argument types. You might need to add explicit...

Get array of values from array of hashes

ruby,hash
I have a array like this arr = [{:id=>1}, {:id=>2}, {:id=>3}, {:id=>4}, {:id=>5}, {:id=>6}, {:id=>7}, {:id=>8}] The result should be result = [1, 2, 3, 4, 5, 6, 7, 8] I used arr.map { |i| i.values }.However, the result is [[1], [2], [3], [4], [5], [6], [7], [8]]. Please help....

Appending an element to a page in VoltRb

html,ruby,opalrb,voltrb
I'm trying to append an element to one of my pages in a Volt project, via opal-browser, like so: if RUBY_PLATFORM == 'opal' require 'browser' $document.body << my_dom_element.to_n end # controller code below Unfortunately, I'm getting an error: [Error] TypeError: null is not an object (evaluating 'value.nodeType') (anonymous function) (main.js,...

Stop SSH password prompts in serverspec

ruby,net-ssh,serverspec
I'm in an environment with authentication tokens, so typically a SSH password is not required. My serverspec tests are always asking me for a password. Is there a way to prevent this? No password required: $ ssh atlspf01 [email protected]:~$ Yet, in serverspec $ rake spec Password: Relevant code in spec_helper.rb...

Recursive solution doesn't iterate correctly

ruby,algorithm,search,recursion
I'm working through a toy problem in Ruby: how to produce all possible 10-digit phone numbers where each successive number is adjacent to the last on the keypad. I've represented the adjacent relationships between numbers, and have a recursive function, but my method isn't iterating through the whole solution space....

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2
I am new to rails 4. I have gone through lots of tutorials and trying to solve below scenario. But still no success. Can anybody point me in the right direction. How to handle associations for below scenario. Scenario: 1. Patient can have many surgeries. 2. Surgery has two types...

whenever gem not working, Rails 4

ruby-on-rails,ruby,ruby-on-rails-3,cron,whenever
I am using Whenever gem to schedule some work on my site. Currently I am working on development environment. I have instaled gem as guide suggests. In schedule.rb every 2.minutes do rake "vip_recomend:give" end In lib/tasks/vip_recomend.rake namespace :vip_recomend do desc "Give vip recomend to ads that are in waiting list"...

Ruby hash with key as hash and value as array

ruby,hash
I am creating a hash, whose key is a hash and the value is an array. E.g., shop = Hash.new items.each do |item| grouping_key = { 'name'=> item['name'], 'value'=> item['value'] } shop [grouping_key] ||= Array.new shop [grouping_key] << item end Here, I am grouping each item based on grouping key....

Dividing by half in ruby to create an effective calculator

ruby,calculator
For the past while I've been working on a calculator, but have run into problems when needing to divide by a half. I'll add the offending bit of code along with a loop to keep it open below. on = true while on == true do half = 1.0 /...