Menu
  • HOME
  • TAGS

Ruby boolean logic: some amount of variables are true

ruby

[a, b, c].count(true) < 2 ........................

Error when trying to install app with mysql2 gem

mysql,ruby-on-rails,ruby,ruby-on-rails-4

The error log says: ld: library not found for -lssl So, you need to install libssl: brew install openssl Hope it helps....

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2

So, the complex part of your situation is that you have one thing (Surgery) that can be of many different types, and the different types have different fields. There are a number of different approaches to this problem, and I don't believe there's wide consensus on the 'best way'. The...

Prevent upvote model from being called for every comment

ruby-on-rails,ruby,database,performance,model

Assuming you have properly set relations # user.rb class User has_many :upvotes end we can load comments, current user and his upvotes: # comments_controller.rb def index @comments = Comment.limit(10) @user = current_user user_upvotes_for_comments = current_user.upvotes.where(comment_id: @comments.map(&:id)) @upvoted_comments_ids = user_upvotes_for_comments.pluck(:comment_id) end And then change if condition in view: # index.html.erb <%...

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

ruby-on-rails,ruby,activeadmin,show

You can write following code instead, and it will work fine. 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')}, #{live["inbound_date"].strftime('%Y-%m-%d')} = #{flight.currency_symbol}#{live["price"]} [#{link_to "Link", "#"}]".html_safe end end end end ...

Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku

Your migration file named should correspond to AddWeightToExercises. It should be accordingly xxxxxxxx_add_weight_to_exercises, where xxxxxxx corresponds to a particular timestamp.

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

You can use something called action_name in Rails 4. action_name gives you the name of the action your view got fired from. Now you can send this property to the method create through a hidden field like following: <%= hidden_field_tag "action_name", action_name %> This line of code will send params[:action_name]...

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

ruby

Not as simple as I did expect. Here is what I came up with: class Hash def hash_merge(other) update(other) do | key, val_self, val_other | case val_self when Hash val_self.hash_merge val_other when Array val_self += [nil] * (val_other.length - val_self.length) val_self.zip(val_other).map { | a, b | a && b ?...

No Method When Importing to Rails via CSV

ruby-on-rails,ruby

You should use << operator, as it's plural association: hotel.contacts << Contact.create(name: row['contact_name']) Note that I removed :hotel_id key from parameters, as it would be redundant (it's already set via association). You can do it also from the other end of association: Contact.create(name: row['contact_name'], hotel: hotel) ...

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

Change required (in github notation): - myFunction(submitArgs()) + myFunction(*submitArgs) The reason that [I assume] myFunction is declared taking two arguments: def myFunction a1, a2 Hence the array must be splatted before passing to it. I wonder how that worked in 1.8....

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

ruby-on-rails,ruby,rack,multipart

Telling it short, this value limits the amount of simultaneously opened files for multipart requests. To understand better what is multipart, you can see this question. The reason for this limitation is an ability to better adjust your app for your server. If you have too many files opened at...

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

ruby

str = <<'TEXT' hello %s \\\hline %s TEXT name = "Graig" msg = "Goodbye" puts str % [name, msg] The heredoc does not have escape chars when it's delimiter is in single quotes. It does have a form of interpolation. The code above has this output: hello Graig \\\hline Goodbye...

Ruby API Call Page Issue

ruby-on-rails,ruby,json,api,httparty

In fact, a quick google led me to this page https://app.enigma.io/api#data which tells me the parameter in question is limit, and that the max is 500. So, it looks like you can't get the data for all rows in one hit. If you really NEED the data for all the...

Using Ruby Pathname to access relative directory

ruby,path,pathname

You need add another level like p = Pathname.new('dir/.') now the directory name is "dir"...

Ruby if else statement one line not working

ruby-on-rails,ruby,ruby-on-rails-4

You do not need to use "if" in the ternary. Change your statement to look like this: <%= current_page?(root_path) ? 'active' : 'inactive' %> ...

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

ruby

When you say :method, you're using some nice syntactical sugar in ruby that creates a new Symbol object. When you throw an ampersand before it (&:method), you're using another piece of sugar. This invokes the to_proc method on the symbol. So, these two things are identical: method_proc = &:method sym...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

Recursive solution doesn't iterate correctly

ruby,algorithm,search,recursion

The first time you enter the adjacencies[to_append].each, you immediately return from the method, therefore the loop will never be executed more than once. You need to return a list of phone numbers instead of just a single phone number build that list somehow in your recursive call ...

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

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller

You can use content_for and yields to create a default in your layout which views can override. # layouts/application.html.erb: <% if content_for?(:banner) %> <%= yield(:banner) %> <% else %> <div id="banner"> <h1>This is the default...</h1> </div> <% end %> /users/signup.html.erb: <%- content_for :banner, flush: true do -%> <!-- move along,...

Heroku RAM not increasing with upgraded dynos

ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku

That log excert is from a one off dyno, a la heroku run console - this is entirely seperate to your web dynos which you may be runnning 2x dyno's for. You need to specifiy --size=2x in your heroku run command to have the one off process use 2x dynos.

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

ruby,file,csv,dir

I believe the problem is with Dir.foreach, not CSV.open. You need to supply a directory to foreach as an argument. That's why you are getting the missing argument error. Try: Dir.foreach('/path/to_my/directory') do |current_file| I think the open that is referenced in the error message is when Dir is trying to...

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

ruby-on-rails,ruby,refactoring

You can change your routes : resources :techs, :only => [:index, :show], shallow: true do resources :cars, only: [:new, :create] collection do get 'part/:part_name' => "techs#part", as: :part end end Then add the action : def part @techs = Tech.joins(:services).where(services: { name: params[:part_name]}) end and the view will be :...

Opal.rb anonymous function in native object

ruby,opalrb

I'm guessing you want to pass a ruby method as a callback to a javascript function, you could try something like this: x = { bar: method(:foo).to_proc } x.to_n But bear in mind that this might not work as intended for class methods ( the context might change on javascript)...

regex to pull in number with decimal or comma

ruby,regex

\d+(?:[,.]\d+)? Try this.This should do it for you....

.split and regular expression in Ruby

ruby,regex

Very well. Taking inspiration from this answer, the regular expression you are looking for is: values.split(/,(?=(?:[^']*'[^']*')*[^']*$)/) This will not work if you have escaped quotes, for example (e.g. "'O\'Reilly\'s car'"). However, this looks a bit like an XY problem. If you want to parse CSV, as it seems, and if...

Combine logic of boolean value & integer in one activerecord model

ruby-on-rails,ruby,activerecord

You can use existing days_lifetime column and put for example -1 for products with unlimited lifetime(I assume 0 is being used for expired products).

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

ruby,serverspec

This behaviour is controlled by RSpec::Core::RakeTask#fail_on_error so in order to have it continue on all hosts you need to add t.fail_on_error = false. I also think that you don't need to rescue. namespace :spec do task :all => hosts.map {|h| 'spec:' + h.split('.')[0] } hosts.each do |host| desc "Run serverspec...

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

ruby

This code will work: ruby -pi -e 'sub(/^/,"New line goes at top\n") if $FILENAME != $F;$F = $FILENAME' file* ...

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

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

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

ruby

It's actually defined inside File::Constants, and thereby documented under the same. Look it up with ri : ri File::Constants Or read the html doc : Module: File::Constants (Ruby 2.2.2)....

Stop SSH password prompts in serverspec

ruby,net-ssh,serverspec

On your configuration, you only pass info about user to ssh_options Assuming that your target host is stored into environmental variable TARGET_HOST and username is stored into USERNAME, you should do something like this: set :ssh_options, Net::SSH::Config.for(ENV['TARGET_HOST']).merge(user: ENV['USERNAME'])...

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

ruby-on-rails,ruby

Don't know what the surrounding code looks like so let's assume your code is the entire body of a method. Then a guard clause might look like this: def some_method return if params[:"available_#{district.id}"] != 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id) delivery_custom_price(district) end ...

Ruby each loop based on array

ruby,sinatra

In your view, you can do something like: <% countries = @airports.group_by{|a| a.first} %> <% countries.each do |country, airport| %> <optgroup label="<%= country %>"> <% airport.each do |a| %> <option value="<%= a[1] %>"></option> <% end %> </optgroup> <% end %> PS: This is just to give you a rough idea,...

How to map browser dialog using capybara/selenium

ruby,selenium,capybara

Where possible, you should try to avoid using the underlying driver directly. By using Capybara's API, you would be (in theory) in a better position if you want to change driver's and there are driver API differences. From Capyabara's project page, the way to handle modal dialogs is: In drivers...

Map with accumulator on an array

ruby,inject

This operation is called scan or prefix_sum, but unfortunately, there is no implementation in the Ruby core library or standard libraries. However, your intuition is correct: you can implement it using Enumerable#inject. (Actually, Enumerable#inject is general, every iteration operation can be implemented using inject!) module Enumerable def scan(initial) inject([initial]) {|acc,...

Using attr_accessor from inside class? [duplicate]

ruby,attr-accessor

That is, because those methods should be called with self: class StringClass def initialize @thing = "old" end attr_accessor :thing def output puts self.thing end def change self.thing = "new" end end ...

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

ruby-on-rails,ruby

Use ::Article to refer to the top-level namespace class, and MyEngine::Article to refer to the engine's class. While using Article alone within the MyEngine namespace will resolve correctly, doing this introduces a couple of pitfalls: It makes it confusing to understand your code as there are multiple references to an...

Ruby access words in string

ruby

What you are doing will access the fourth character of String s. Split the string to an array and then access the fourth element as follows. puts s.split[3] Note: Calling split without parameters separates the string by whitespace. Edit: Fixing indexes. The index starts from 0. That means s.split[3] will...

Allowing some enabled and disabled option on collection_select

ruby-on-rails,ruby

collection_select internally relies on options_from_collection_for_select helper. Rather than using the collection_select directly, you can use select and pass the result of a options_from_collection_for_select call. The reason you may want to call options_from_collection_for_select directly, is because this method also accepts an optional selected parameter that could be used to pass a...

Undefined local variable post

ruby-on-rails,ruby,variables,undefined,local

You need to use partial: when you pass locals to a partial as follows: <%= render partial: 'post', locals: { post: post, user: @user} %> I hope this will help you....

Error installing gem twitter on Ubuntu 15.04

ruby-on-rails,ruby,ubuntu,twitter

You are getting this error because there is no ruby development environment installed. Development environment is needed to compile ruby extensions, You should install development first using command below: $ sudo apt-get install ruby-dev ...

Installing GitLab CI Runner on Raspberry Pi 2 (Raspbian)

ruby,gitlab,raspberry-pi2

Managed to install an unofficial runner. Guide here: https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-manually.md...

how to define extra method for rails form text_field

ruby-on-rails,ruby

You need a virtual attribute, which is done using attr_accessor attr_accessor is a ruby method for creating getter and setter methods. This basically means you're able to create a series of virtual attributes for use in your models Class Table < ActiveRecord::Base attr_accessor :dimensions end ...

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

ruby-on-rails,ruby,ruby-on-rails-4

In your associations instead of fac_allocs you need to use a symbol because rails is looking a variable or method named fac_allocs instead of your associated model has_many :facs, through: :fac_allocs ...

Keep leading zeroes when converting string to integer

ruby

Short answer: no, you cant. 2.1.5 :001 > 0001 => 1 0001 doesn't make sense at all as Integer. In the Integer world, 0001 is exactly as 1. Moreover, the number of leading integer is generally irrelevant, unless you need to pad some integer for displaying, but in this case...

Having trouble calling a Proc within a Method within a Class

ruby,proc

It's about the context. In the 2nd example you are putting the ring proc inside the class, so when you actually call ringtime.hourlyRing ring, ring is not defined in that scope. You could alter the code to: class GrandfatherClock def hourlyRing ring time = Time.now.hour%12; hour_set =[12, 1, 2, 3,...

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

sql,ruby,gis,postgis

It looks like you are trying to use ST_Contains on geography types, but that function only works on geometry types. If you are OK with the intersects spatial relation (see DE-9IM), then use ST_Intersects(geography, geography)....

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

javascript,arrays,ruby,iteration

You are looking for the Array.prototype.some method: var match = arr.some(function(w) { return w.indexOf('z') > -1; }); ...

Elasticsearch advanced search

ruby-on-rails,ruby,search

I will prefer to do this in your action. tags = params[:q].present? ? params[:q].scan(/#[^ #]+/).collect{|tag| tag.gsub(/#/, '')} : [] now you can use this array of tags in search function...

Seach by class in Nokogiri nodeset

ruby,xpath,nokogiri

Assuming that the class name is stored into class_name, I think that doc.xpath("//*[contains(concat(' ', normalize-space(@class), ' '), ' #{class_name} ')]") is what you're looking for. This will match all the elements that contain class_name into their classes, ie if class_name is 'box', then it will match both elements like div...

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

Grab the host's articles from the engine: @host_app_articles = ::Article.all #refers to top-level namespace class Render it from the view inside the engine: <% @host_articles.each do |article| %> <%= render file: "/app/views/articles/_article", locals: {article: article} %> <% end %> And just for completion, here is what the partial might look...

RoR: removing sensitive field from response

ruby-on-rails,ruby,rails-activerecord

You can use the as_json to restrict the attributes serialized in the JSON response. format.json { render json: @my_objects.as_json(only: [:id, :name]), ...} If you want to make it the default, then simply override the method in the model itself class MyObject def serializable_hash(options = nil) super((options || {}).merge(only: [:id, :name]))...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many

Take a look at merit gem. Even if you want to develop your own badge system from scratch this gem contains plenty of nice solutions you can use. https://github.com/merit-gem/merit

Split an array into slices, with groupings

arrays,ruby,enumerable

Yes, this bookkeeping with i is usually a sign there should be something better. I came up with: ar =[ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name:...

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter

If you express the relation properly, ActiveRecord will do it for you class Tweet belongs_to :original_tweet, class_name: Tweet has_many :retweets, class_name: Tweet, dependent: :destroy, inverse_of :original_tweet end Tweet.last.destroy # will now destroy dependents ...

For loop with flexible stop variable

ruby

Normally we'd use a loop do with a guard clause: x = 1 loop do break if x >= y x += 1 ... end Make sure y is larger than x or it'll never do anything. y can change if necessary and as long as it's greater than x...

Get the actual value of a boolean attribute

ruby,page-object-gem,rspec3,rspec-expectations

The Page-Object gem's attribute method does not do any formatting of the attribute value. It simply returns what is returned from Selenium-WebDriver (or Watir-Webdriver). In the case of boolean attributes, this means that true or false will be returned. From the Selenium-WebDriver#attribute documentation: The following are deemed to be “boolean”...

whenever gem not working, Rails 4

ruby-on-rails,ruby,ruby-on-rails-3,cron,whenever

PATH problem may be, by putting the following at the top of the schedule.rb, ensure correct bundle path env :PATH, ENV['PATH'] Or try to add following if above one not work. env :GEM_PATH, ENV['GEM_PATH'] ...

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

jquery,ruby-on-rails,ruby,ruby-on-rails-4,rubygems

Everything is OK from your side. You said that you're on Windows 7, I also experienced this problem once when I needed to run rails on windows for some reason. Than I found an answer here which helped me to get out of this problem. Actually coffee-script-source, v 1.9.x gives...

metriks log to file not working

ruby,code-metrics

You should either pass in your own registry while instantiating Metriks::Reporter::Logger or use the deafult registry (Metrics::Resgitry.default) if you are using a logger to log metrics. Also the default log write interval is 60 seconds, your code completes before that so even if everything is setup okay it won't get...

Get array of values from array of hashes

ruby,hash

You should flatten the result, to get your desired output : arr.flat_map { |i| i.values } Read flat_map. I don't know actual intention of yours, still if you want to collect all ids, you can write : arr.collect { |h| h[:id] } ...

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

ruby-on-rails,ruby,json,nokogiri

namespace :scraper do desc "Scraper" task scrape: :environment do require 'open-uri' require 'nokogiri' require 'csv' require 'json' url = "https://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers" page = Nokogiri::HTML(open(url)) page.css('td b a').each do |line| puts line.text # "Spanish" Language.create(language: line.text) end end end ...

Get value from string representing local variable [duplicate]

ruby,local-variables

You can use eval. variable = 22 eval("variable") # => 22 However eval can be nasty. If you dont mind declaring an instance variable, you can do something like this too: @variable = 22 str = "variable" instance_variable_get("@#{str}") # => 22 ...

How do I change the Rails timezone on Windows?

ruby-on-rails,ruby

Time.now returns the time from you system clock. You can test this by going into Windows and changing the timezone. You'll find that Time.now has different values depending on the setting. Time.zone.now will return the time based on your rails application setting....

a repeated permutation with limitations

arrays,ruby,permutation

Approach I think recursion is the way to go here, where your recursive method looks like this: def recurse(n,t) where n is the number of elements required; and t is the required total. If we let @arr be the array of integers you are given, recurse(n,t) returns an array of...

Ruby hash with key as hash and value as array

ruby,hash

Your initial code is equivalent to shop = items.group_by do | i | {'name' => i['name'], 'value' => i['value'] } end To add the color to the key hash, simply do shop = items.group_by do | i | {'name' => i['name'], 'value' => i['value'], 'color' => i['color'] } end Now,...

String#scan not capturing all occurences

ruby,regex

The reason is that after finding the first result, the regex engine continues its walk at the position after this first result. So the zero at the end of the first result can't be reuse for an other result. The way to get overlapping results is to put your pattern...

How do I pass a hash from commandline?

ruby

p.option :addsound, "add sound" ^ this makes it a flag (true or false) What you want is make it into a switch whose value is the next argument: p.option :addsound, "add sound", default: "" ^ this makes it a switch, the string value will be assigned to options[:addsound] newsound =...

Ruby - at least one item in array ALSO in line

ruby,regex

Couple of ways. Speed may depend on the size of your array and line. Might want to run some benchmarks to see: > a = ["/Item A/", "/Item B/"] > l = "Here's a line of text that includes /Item B/" Then using any?: > a.any?{|e| l.index(e)} => true Or...

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

javascript,ruby-on-rails,ruby,xml,api

Net::HTTP is Ruby's built in library for sending HTTP requests. Rails also has built in features for serializing models to XML. Lets say you bind your form to a User model: class User < ActiveModel::Base # attr_accessor is not needed if these are real DB columns. attr_accessor :firstname attr_accessor :surname...

Get X days out of an Array

ruby,ruby-on-rails-4

I would do: def get_days(wkn, *desired_days) get_week = Model.week(2) get_days_of_week = get_week.select { |x| desired_days.include? x.strftime("%A") } end ...

RSpec test for rake task

ruby-on-rails,ruby,rspec,rake-task

A couple things. First off, you should put created_at in the create method: user.items.create(description: "Old Item", created_at: 12.days.ago). Second, you need to call user.reload in order for the changes from your rake task to be available. So it should look like this: user.reload expect(user.items.count).to eq 1 etc...

Iterating over EncryptedDataBagItem in Chef Recipe

ruby,json,chef,devops

why not something like: decrypted_item = data_bag_item('secrets', 'passwords', node['my_repo_name']['secret_key_file_path']) file '/opt/me/passwords.json' do content decrypted_item.to_hash.to_json mode 600 end ...

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

ruby,rspec,mocking

For your workflow, I think it's going to work better to use a class_double than than to stub the Hashes class directly. allow(Hashes) is always going to require that the Hashes constant is defined. It's simply how Ruby works and RSpec can't do anything about that. With a class double,...

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

ruby-on-rails,ruby

You can try : dateLabels = <%= raw @mapped_dates.as_json %>; This will return ["Jan 1", "Jan 2", "Jan 3", ... ] For ActiveSupport::TimeWithZone problem, please do - In config/initializers/time_zone.rb class ActiveSupport::TimeWithZone def as_json(options = {}) if ActiveSupport::JSON::Encoding.use_standard_json_time_format xmlschema else %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) end end end ...

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

ruby-on-rails,ruby

No, there is not. parameterize is a lossy conversion, you can't convert it back. Here's an example. When you convert My Awesome Pizza into my-awesome-pizza you have no idea if the original string was My Awesome Pizza MY AWESOME PIZZA etc. This is a simple example. However, as you can...

Appending an element to a page in VoltRb

html,ruby,opalrb,voltrb

Ok, so the problem is that the code you have is being loaded as soon as the compiled .js file loads. You need to run the code once the DOM is ready. The easy way to do this in volt is to run it on a {action}_ready method: module Main...

Rails add hash into existing hash

ruby,ruby-on-rails-4

The solution is convert to hash result after select from db using @user.as_json a = Hash.new a[:profile] = @user.as_json a[:profile][:contacts] = @user.contacts.all ...

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

ruby,process,output,fork,spawn

There are a whole bunch of ways to run commands from Ruby. The simplest for your case is to use backticks, which capture output: `sleep 10; date` # "Tue Jun 23 10:15:39 EDT 2015\n" If you want something more similar to Process.spawn, use the open3 stdlib: require 'open3' stdin, stdout,...

Switch between windows with frames

ruby,capybara

The exception is occurring in the within_frame method when trying to switch back to the parent frame. It seems like a bug, so th best thing to do would be to raise it as an issue in the Capybara project. In the meantime, the quickest solution would be to rescue/ignore...

convert JSON array to Ruby Hash (of hashes)

ruby,json

My question did not show the full string I was trying to JSON.parse. I only put what I was trying to parse. I accidentally left some floating data before the JSON part of my string. Now that I have deleted that, it is working.

Couldn't find User with 'id'=show

ruby-on-rails,ruby,devise

The show action depends on looking up an id. Since you're hitting the URL /users/show, it assumes you're trying to look up a user with id of show. Instead, you should be going to a url like /users/1 to trigger the show action. The Rails guide on routing has a...

Combining items into interval bins by timestamps

javascript,ruby-on-rails,ruby

Round the time down to its hour and build up a new hash with the aggregate counts. If you want the user to select a time period, just pick the strftime format based on the bucket size. You could do math on the Time object, but you're going to format...

How to flatten a structure of embedded Set and Hash

ruby,recursion

Recursion is your friend: require 'set' def t_h(inp, prefix = []) if (inp.is_a?(Hash)) result = [] inp.each do |k,v| pprefix = prefix.dup result << t_h(v, pprefix << k) end return result.flatten(1) elsif (inp.is_a?(Set)) result = [] inp.each do |el| result << t_h(el, prefix) end return result.flatten(1) else pprefix = prefix.dup...

Dividing by half in ruby to create an effective calculator

ruby,calculator

Your to_i call is switched around here. print("What is the legnth of the base? ").to_i base = gets.chomp("base") Should be the other way 'round. print("What is the length of the base? ") base = gets.chomp("base").to_i Further, chomp will attempt to remove any occurrences of base or height from the string....

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4

You should pass actions to the included block and perform_search_on to the class_methods block. module Searchable extend ActiveSupport::Concern class_methods do def perform_search_on(klass, associations = {}) ............. end end included do def filter respond_to do |format| format.json { render 'api/search/filters.json' } end end end end When your Searchable module include a...

Rails basic auth not working properly

ruby-on-rails,ruby,authentication

@user.keys.each do |key| username == key.api_id && password == key.api_key end This piece of code returns a value of .each, which is the collection it's called on (@user.keys in this case). As it is a truthy value, the check will pass always, regardless of what are the results of evaluating...

User path with username

ruby-on-rails,ruby,path,user,friendly-id

Artyom you can use the friendly-id gem if you want to make this process easier on you. Ryan Bates has a Railscast on it as well. That way you can use strings as ids (i.e. your username) in the url: http://localhost:3000/articles/hello-world Let me know if you have any questions, -Dave...

Loop until i get correct user

ruby,redis

Change if to while: while ["user_4", "user_5"].include?(@randUser = @redis.spop("users")) do @redis.sadd("users", @randUser) end $user_username = @redis.hget(@randUser, "username") $user_password = @redis.hget(@randUser, "password") Please note, that you actually mixed up receiver and parameters on Array#include?...

Same enum values for multiple columns

ruby-on-rails,ruby,enums

Maybe it makes extract the planet as another model? def Planet enum type: %w(earth mars jupiter) end class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet' end You can create a PlanetEdge by using accepts_nested_attributes_for: class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet'...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations

Found this : Validating nested association in Rails (last chapter) class User belongs_to :organization, inverse_of: :users validates_presence_of :organization_id, :unless => 'usertype==1' end class Organization has_many :users accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true end The documentation is not quite clear about it but I think it's worth a try....

How could I padding spaces to a fix length

ruby

You should use ljust: arr = [477, 4770] strings = arr.map { |number| number.to_s.ljust(5) } # => ["477 ", "4770 "] Good luck!...

Ruby- get a xml node value

ruby,xml

Try to use css instead of xpath, this will work for you, doc = Nokogiri::XML(response.body) values = doc.css('Name').select{|name| name.text}.join',' puts values => Ram,Sam ...

Rails less url path change

ruby-on-rails,ruby,url,path,less

You should use the font_url, and put the font in app/assets/fonts @font-face { font-family: 'SomeFont'; src: font_url("db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } ...

How to use Rails #update_attribute with array field?

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord

I don't think update_attribute is going to be useful as it will replace the array with the new value rather than append to it (but see better explanation below in --Update-- section). I'm not sure what best practices are here, but this should work to just add something if it...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

It's not "through Hash", it's "array access" operator. To implement it, you need to define methods: def [](*keys) # Define here end def []=(*keys, value) # Define here end Of course, if you won't be using multiple keys to access an element, you're fine with using just key instead of...