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 ...
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...
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)....
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...
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:...
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'])...
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...
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...
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 ...
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"); //... } ...
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...
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...
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,...
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 <%...
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...
Your migration file named should correspond to AddWeightToExercises. It should be accordingly xxxxxxxx_add_weight_to_exercises, where xxxxxxx corresponds to a particular timestamp.
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
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.
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...
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...
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 ...
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...
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...
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'] ...
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 ...
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 ...
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 :...
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,...
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 ...
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) ...
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 ...
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,...
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 ...
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'...
This code will work: ruby -pi -e 'sub(/^/,"New line goes at top\n") if $FILENAME != $F;$F = $FILENAME' file* ...
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,...
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...
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....
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 ...
javascript,arrays,ruby,iteration
You are looking for the Array.prototype.some method: var match = arr.some(function(w) { return w.indexOf('z') > -1; }); ...
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,...
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 ?...
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]))...
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 ...
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 ...
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....
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...
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 ...
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 ...
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...
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”...
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...
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.
You should use ljust: arr = [477, 4770] strings = arr.map { |number| number.to_s.ljust(5) } # => ["477 ", "4770 "] Good luck!...
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...
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 =...
Managed to install an unofficial runner. Guide here: https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-manually.md...
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...
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...
You are trying to write a python code using ruby syntax. This is not a best approach to GTD. Slashes are handled right-to-left, yielding not what you expected. As soon as one finds herself putting three or more backslashes inside the string, she should admit, she’s doing it wrong. At...
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...
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...
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...
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...
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,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' %> ...
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....
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 ...
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...
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...
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...
You need add another level like p = Pathname.new('dir/.') now the directory name is "dir"...
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-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-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).
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...
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]...
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....
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...
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?...
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-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...
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...
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,...
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)...
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...
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,...
[a, b, c].count(true) < 2 ........................
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...
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...
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)....
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....
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] } ...
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...
\d+(?:[,.]\d+)? Try this.This should do it for you....