In our Rails Application, we are uploading images using Paperclip gem. I would like to know whether there is anyway to find DPI value of such an uploaded image?
mercredi 6 mai 2015
Find resolution of an image in dpi value uploaded using paperclip
date based condition check in ruby
I want to check a category based on the age of a member. My test are looking like this:
it "should return 'CATEGORY B' if member turn 15 on the 01-11-2015" do
Timecop.freeze(Date.parse("01-11-2015"))
@member.date_of_birth = "2000-11-01"
expect(@member.category).to eq('CATEGORY B')
end
it "should return 'CATEGORY C' if member turn 15 on the 31-10-2015" do
Timecop.freeze(Date.parse("01-11-2015"))
@member.date_of_birth = "2000-10-31"
expect(@member.category).to eq('CATEGORY C')
end
and my method in the model is looking like this:
def category
local_age = age
next_november = "01-11-#{Date.today.year}"
last_day_in_oktober = "31-10-#{Date.today.year}"
if local_age < 7 then
'CATEGORY A'
elsif local_age >= 7 && local_age < 15
'CATEGORY B'
elsif local_age > 15 && local_age < 40
'CATEGORY C'
elsif local_age >= 40
'CATEGORY D'
end
end
How can I implement the and freeze the time in the model in order pass the tests? Any idea
Check if local variable is defined given it's name as string in ruby
Can I check if a local variable is defined given it's name as string?
I know there is the function defined?, but you have to give the variable itself.
Example:
a = 'cat'
print defined?(a) # => "cat"
print defined?(b) # => nil
What I need is:
a = 'cat'
print string_defined?("a") # => "cat"
print string_defined?("b") # => nil
Or something like that. I can't find it in the docs...
I tried to use respond_to?, but doesn't seems to work...
Ruby Sinatra - How to capture post json data and save to file
How do I capture a Json data from POST route and save it to file? I have simple ruby sinatra code as below.
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'json'
post '/' do
values = JSON.parse(request.env["rack.input"].read)
# How do I save "values" of JSON to file..
end
How to add front end validation in bootstrap-wysihtml5-rails
I have integrated the bootstrap-wysihtml5 editor to description section in my rails application. Now I want to add the client side validation so that it would validate the presence of description field. I used bootstrap-wysihtml5-rails gem.
Thanks in advance.
How can I check whether new page is completed loaded or not using watir
Is there any way Can I check whether a particular page completely loaded or not using WATIR?
I tried with browser.status but it's not printing anything
Ruby ternary operator and method call
I am using ruby 2.1.5, facing some problem with ternary operator
Syntax error
request.xhr? ? render :json => "success" : redirect_to index_url
working
request.xhr? ? render(:json => "success") : redirect_to(index_url)
Can some please explain How its works and why above one not working? Thanks in advance
Ruby on Rails: Categories not working or sorting
The posts and categories are not agreeing on something and I'm not sure what it is. What am I doing wrong?
As soon as I click a category nothing changes but the url to http://localhost:3000/posts?category=Physics
class Post < ActiveRecord::Base
belongs_to :category
# ...
end
class Category < ActiveRecord::Base
belongs_to :posts
# ...
end
Here is the Posts Controller:
class PostsController < ApplicationController
def index
if
params[:category_id].blank?
@posts = Post.all.order("created_at DESC")
else
@category_id = Category.find_by(name: params[:category]).id
@posts = Post.where(category_id: @category_id).order("created_at DESC")
end
end
# ...
def post_params
params.require(:post).permit(:title, :link, :description, :category_id)
end
Here is the index file:
<% Category.all.each do |category| %>
<%= link_to category.name, posts_path(category: category.name) %>
<% end %>
<% @posts.each do |post| %>
<%= link_to post.title, post %>
<%= link_to time_ago_in_words(post.created_at) + " ago", post %>
<% end %>
This is the migration for Posts:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.string :link
t.text :description
t.timestamps null: false
end
end
end
This is the migration for AddIdToPosts
class AddIdToPosts < ActiveRecord::Migration
def change
add_column :posts, :category_id, :integer
end
end
This is what console told me about the last post:
irb(main):008:0> Category
=> Category(id: integer, name: string, created_at: datetime, updated_at: datetime)
irb(main):009:0> @post = Post.last
Post Load (17.0ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT 1
=> #<Post id: 3, title: "Testing", link: "",
description: "testing", created_at: "2015-05-06 07:08:36",
updated_at: "2015-05-06 07:08:36", user_id: 1, category_id: 1>
Ruby on Rails uncaught throw :warden with Devise.
I have a very strange problem in my Ruby on Rails application. I have controller that looks like this:
class PersonReportsController < ApplicationController
include ActionController::Live
load_and_authorize_resource except: [:index]
def index
#some code
end
end
and when I try to access it as an unlogged user application throws following error:
uncaught throw :warden
But when I delete from my controller:
include ActionController::Live
everything works fine... Any ideas how to solve this problem?
javascript code disappears on source window after refreshing page in rails 3 using jquery
Here is a unique problem I am not able to find solution to. I write a small black of code given as below.
$(document).ready(function () {
alert("Page loaded");
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
$(document).on('visibilitychange', function () {
if (document.hidden == false) {
console.log("gotcha");
location.reload();
}
console.log(document.hidden, document.visibilityState);
});
}
});
I was working only for ipad(the bug was device specific) but now I face the issue that this code disappears after refreshing page a few times in all other machines also.
Solutions attempted till now:
- I added this within the tag with and without specifying type="text/javascript" in the beginning of the page and in the end as well. Astonishingly this code disappears the same way and few other variables defined for javascript code within the tag remains same and visible.
-
I added a file separately with this block of code in it and included that file with <%= javascript_include_tag %> in two ways.
2.1 Simply adding this tag in my separate view file.
2.2 Adding it using "content_for" helper and thus calling it with yield and specified name in the application.html.erb file.
3.When I add this in my appliaction.js within assets folder it works but I need this specifically for a particular action else it will reduce my site's performance .
I do not understand whether the issue is with the code or what. I will be really thankful if someone provides a required solution to it.
I am using following things in it
ruby 1.9.3
rails 3.2.12
running server with foreman
memcache
Foreman conditional running processes
I have a foreman app with a Procfile like this
web: bundle exec rails s
custom_process: bundle exec rake custom:process
faking_custom_process: bundle exec rake custom:faking_process
And I want to run custom_process or faking custom_process depends on my needs:
foreman start # run web & custom_process
FAKING_PROCESS # run web & faking_custom_process
Yes, I know about ability of running like that foreman start -c faking_custom_process=0, but this is more difficult than I expect, right?
How can I connect Aweber to my Rails app using OAuth?
I'm trying to integrate my Rails app with Aweber via OAuth, using the official aweber gem.
If I follow their flow in the Rails console, I can get an access token, no problems:
oauth = AWeber::OAuth.new(ENV["AWEBER_CONSUMER_KEY"], ENV["AWEBER_CONSUMER_SECRET"])
puts oauth.request_token.authorize_url
# => http://ift.tt/1JpWwfi
Then I visit that URL, type in my credentials, get a verification code, and go back to the rails console:
oauth.authorize_with_verifier 'xxxxxx'
# => #<OAuth::AccessToken>
Success!
The problem is, I want to do this in the real world, not just at the console, which means my Ruby code needs to be broken up into two separate actions. First, there's the controller action which redirects to Aweber's Oauth page:
def aweber
oauth = AWeber::OAuth.new(ENV["AWEBER_CONSUMER_KEY"], ENV["AWEBER_CONSUMER_SECRET"])
redirect_to oauth.request_token(oauth_callback: "http://ift.tt/1H0hUKK").authorize_url
end
Then there's the action which gets the access token after the user has input their credentials and been redirected:
def aweber_callback
oauth = AWeber::OAuth.new(ENV["AWEBER_CONSUMER_KEY"], ENV["AWEBER_CONSUMER_SECRET"])
oauth.authorize_with_verifier(params[:oauth_verifier])
end
When I do it this way, the final line (authorize_with_verifier) always raises #<OAuth::Unauthorized: 401 Unauthorized>.
Seems like the problem is that I'm initializing the oauth variable twice, meaning I have two unrelated instances of AWeber::Oauth ... and only the instance of AWeber::Oauth that generated the authorize_url can get the access token. But I can't get the *same* instance in bothaweber_callbackandaweber` because I'm dealing with two completely different threads and instances of the controller.
When I inspect oauth, I can see that the internal variables oauth.request_token.params["oauth_token"] and oauth.request_token.params["oauth_token_secret"] are different in each oauth, which I'm guessing is the cause of the problem. I can get the 'correct' oauth_token from the params (params[:oauth_token]), but I can't figure out how to get the correct oauth_token_secret (not to mention that manually setting instance variables like this feels very hacky and is probably not the best approach.)
How can I generate an access token?
Ruby on rails plugin
I´m new in Ruby on rails. I´m trying to write a plugin, place in in project menu, and insert some data per projects. but there is a problem in my plugin. I have written the plugin, and add a tab in project menu. the plugin show something, but now I wanna edit the data. in the page index.html.erb, show data. I have added a link to edit data. I add a page edit.html.erb. but when I click on the edit link, show that the page can not found. Can anyone help me_
Get sum of numbers within range (from 0 to user input)
This is the code i am using, its purpose is for the user to enter an integer, the program will then take the sum of all the numbers up to and including the one entered. There is probable an easier way to do this
sum = 0
puts "please enter a number"
counter = gets.chomp.to_i
begin
sum += counter
counter -= 1
end while counter == 0
Ruby on Rails on Windows 'SQLite' installing error
I am facing this problem any one can help me. Ruby version 2.0.0 and rails version 4.2.1.
I have an array called p1 as below:
p1= [512, 2048]
I'm passing p1 to test method as below:
test(p1)
test method definition looks as below:
def test(value)
if value.kind_of?(Array)
value.each do |proto|
puts"******#{proto}"
end
end
end
The above code execution is throwing the error:
#<NoMethodError: undefined methodto_i' for [512, 2048]:Array>
What could be the reason for it?
Get Postgres-activerecord setup to work both locally and in Heroku
I'm automating DB creation (with a Rakefile in a Sinatra App).
I would like to be able to run the rakefile from my Linux user "pete" (eg pete@pete_laptop: /path $ rake db:create) AND from Heroku.
It comes down to the settings in my config/database.rb:
ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:port => db.port,
# pete@ubuntu_14.04_laptop--------
# :username => 'pete',
# :password => 'password',
# OR
# heroku -----------------
# :username => db.user,
# :password => db.password,
:database => DB_NAME,
:encoding => 'utf8'
)
If I use the pete@ubuntu_laptop settings, the database works in localhost but not in Heroku, If I use the heroku settings, the database works in localhost but not in Heroku.
How can I setup this file/my ubuntu laptop so that the app works both on localhost & in Heroku?
Cheers,
Pete
Scope on empty association
I'm trying to create a scope looking at empty association.
I've 4 classes : User, Idea Project and UserJoins.
More than one user can have the same idea or the same project.
I would like to create a scope to isolate users without ideas.
Idea.rb
has_many :user_joins
has_many :users, through: :user_joins
Project.rb
has_many :user_joins
has_many :users, through: :user_joins
User.rb
has_many :user_joins
has_many :ideas, through: user_joins, source: :imaginable, source_type: 'Idea'
has_many :projects, through: user_joins, source: :imaginable, source_type: 'Project'
scope :without_ideas, ->{
# I'm stuck here.
}
UserJoin.rb
belongs_to :imaginable, polymorphic: true
belongs_to :user
I'm using Rails 3.2.17 and Ruby 2.0.0
Does anyone have an idea to solve this ?
mardi 5 mai 2015
Looking to Pinged a Series of Servers on a Subsecond Basis and Got a Response for Each
I'm trying to figure out the solution to what seems like a simple problem. I have a series of servers that I'd like to ping and get a response from which I will parse and present to the user. I've looked at a bunch of ruby frameworks and Gems, and none-seem like a perfect fit. Currently, I'm using:
- Sinatra
- Passenger
- Nginx
- Docker
The servers will likely be behind a firewall, and only visible to the node I'm running in the same group, so Javascript on the browser does not feel like a fit. Is there a known pattern for doing something like this?
How to use with_options for conditional validation
How can I use with_options for conditional validation ?
My code is
with_options if: (AppUser::User.creator=="is_admin") do |admin|
admin.validates :first_name, :presence => true
admin.validates :last_name, :presence => true
end
I have already set creator method in application controller.
before_action :set_global_user
def set_global_user
if current_admin
AppUser::User.creator= "is_admin"
elsif current_user
AppUser::User.creator= "is_user"
else
AppUser::User.creator=nil
end
end
but I am getting
undefined method `validate' for false:FalseClass
what is wrong with this code.
Rails Undefined Method in an unknown way
I cloned a project that runs just fine. I did the bundle install, bundle update, db:create, db:migrate, and whatnot.
Now when I run http://localhost:3000/orders/new it returns a NoMethodError in Admin::Orders#new
I have this as part of my code under model/admin/area.rb
has_many :admin_accounts, :class_name => 'Admin::Account'
validates :name, :presence => true
validates :timezone, :presence => true
validates :time_offset, :presence => true
validates :shift_time1, :presence => true
validates :shift_time2, :presence => true
validates :unit_price_12, :presence => true
validates :unit_price_24, :presence => true
def next_shift_time_from_now
current_time = Time.zone.now
next_shift_time(current_time)
end
def next_shift_time(time)
shift1 = time.change(hour: self[:shift_time1].hour)
shift2 = time.change(hour: self[:shift_time2].hour)
get_shift(time, shift1, shift2)
end
And this under my accounts.rb
require 'digest/md5'
before_save :encrypt_password
after_initialize :default_values
has_many :admin_orders, :class_name => 'Admin::Order'
belongs_to :admin_areas, :class_name => 'Admin::Area', :foreign_key => 'area_id'
under new.html
<div class="page-header clearfix">
<div class="pull-right"><%= link_to 'Back', orders_path, class: "btn btn-primary btn-sm" %></div>
<h3 class="pull-left">
Creating New Order
</h3>
</div>
<%= render 'form' %>
and this under _form.html.erb which has the error
<div class="form-group field-bottom-container">
<label id="nextShiftTime">Next Shift Time</label>
<div>
<% @user = Admin::Account.find($user_id) %>
<%= @nextShiftTime=format_datetime(@user.admin_areas.next_shift_time_from_now) %>
</div>
</div>
The error is this line: <%= @nextShiftTime=format_datetime(@user.admin_areas.next_shift_time_from_now) %>
which returns... undefined method `next_shift_time_from_now' for nil:NilClass
Is there anything I must configure to fix this? I think there's nothing wrong with the code since it worked well previously and upon recent clone, with no changes with the codes i might add, the program is causing this error.
How to install ruby on rail application as a plugin in my application?
I am already using open source RoR application. Now I have to create plugin. In that plugin the features I want to use are available in other application. So i want to use that. How can it be done ?
What should be stored in DB when converting site into rails [on hold]
I believe this is more of a subjective question than not, that being said, I am much newer to rails than a lot of you, so I trust your opinion more than my own. Basically I've been talking to someone I know about redoing there website into a rails app, but I am not sure how the best way to go about setting up the database would be. Here is a link to the site I will be remaking http://ift.tt/1OY6mvK.
My question to you is, what all belongs in a database? My first thought is to create two main tables in the db, sections and articles, and have each article belong to a section. I will store all of the html for the content of each separate pages in the db under a certain section (for instance the "welcome", "FAQs", "Contact Information", and all other links under the about dropdown menu will be separate articles stored in the db which belong to the "About" section.)
**Update 5/05/2015 2:37 PM CDT I should clarify that when I say I will post the html for each of those pages in the database, I do not mean ALL of the html on that given page, just the content on those pages that is unique to that page (so headers, menu bars, etc. will not be stored in the database)
However, I'm beginning to wonder if storing all that html and text in a database would be too much, or would be bad practice, and if it is better to just create separate html files for each page, too make it easier to style text and create tables within text and stuff like that. I see pros and cons to both sides, a huge pro, for example, is the fact that if I did store it in the database I would not need to create 30+ HTML files, and could just pass in different Articles from the database into a preformatted page.
So I'm just looking for some advice on what you guys think is the best way to go about this project!
Remove array elements that are present in another array
There is a list of words and list of banned words. I want to go through the word list and redact all the banned words. This is what I ended up doing (notice the catched boolean):
puts "Give input text:"
text = gets.chomp
puts "Give redacted word:"
redacted = gets.chomp
words = text.split(" ")
redacted = redacted.split(" ")
catched = false
words.each do |word|
redacted.each do |redacted_word|
if word == redacted_word
catched = true
print "REDACTED "
break
end
end
if catched == true
catched = false
else
print word + " "
end
end
Is there any proper/efficient way?
Getting error while executing and calabash program
Hi I am getting the below error
D:>calabash-android run d:\Android\Apk_Files\EriBank.apk C:/Ruby21/lib/ruby/2.1.0/rubygems/dependency.rb:298:in to_specs': Could not fi d 'cucumber' (~> 1.3.17) - did find: [cucumber-2.0.0] (Gem::LoadError) from C:/Ruby21/lib/ruby/2.1.0/rubygems/specification.rb:1295:inblock n activate_dependencies' from C:/Ruby21/lib/ruby/2.1.0/rubygems/specification.rb:1284:in each' from C:/Ruby21/lib/ruby/2.1.0/rubygems/specification.rb:1284:inactiva e_dependencies' from C:/Ruby21/lib/ruby/2.1.0/rubygems/specification.rb:1266:in activa e' from C:/Ruby21/lib/ruby/2.1.0/rubygems/core_ext/kernel_gem.rb:54:inge ' from C:/Ruby21/bin/calabash-android:22:in `'
Please help me out if anyone knows any solutions for this.
In ruby console, how to update instance variable?
I have a model named "Person". In ruby console, I first declare an instance of Person, then I update the attributes, then save.
person = Person.last
person.name = "jeff"
person.save
After doing these, I got message like this:
(9.9ms) BEGIN
(7.5ms) ROLLBACK
=> false
What are "BEGIN", "ROLLBACK", "false" refers to separately? I googled, but nothing came out.
Push value to model when created - Rails
I am trying to set the inputter_id value automatically to the id for for the inputter_type corresponding to "Medical team" in a form if the user is a current_clinician:
def create
esas_assessment_params = params.require(:esas_assessment).permit(:patient_id, :clinician_id, :time, :year, :month, :day, :inputter_name, :inputter_id, :pain, :pain_comment, :tiredness, :tiredness_comment, :drowsiness, :drowsiness_comment, :nausea, :nausea_comment, :lack_of_appetite, :lack_of_appetite_comment, :shortness_of_breath, :shortness_of_breath_comment, :depression, :depression_comment, :wellbeing, :wellbeing_comment, :other_symptom_id, :other_symptom_score, :other_symptom_comment, :esas_comment)
@esas_assessment = EsasAssessment.new(esas_assessment_params)
if current_clinician
@esas_assessment.clinician = current_user.clinician
@esas_assessment.inputter_name = current_user.clinician.full_name
@esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team')
else
@esas_assessment.patient = current_user.patient
@esas_assessment.clinician = current_user.patient.clinician
end
if @esas_assessment.save
redirect_to esas_assessments_path, notice: "ESAS assessment submitted!"
else
render "new", alert: "ESAS assessment not submitted!"
end
end
or more simply:
def create
esas_assessment_params = params.require(:esas_assessment).permit!
@esas_assessment = EsasAssessment.new(esas_assessment_params)
@esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team')
if @esas_assessment.save
redirect_to esas_assessments_path, notice: "ESAS assessment submitted!"
else
render "new", alert: "ESAS assessment not submitted!"
end
end
in the first example the lines to set the @esas_assessment.clinician value automatically to the current_user.clinician and setting the inputter_name both work but the inputter_id doesn't.
My EsasAssessment model is:
EsasAssessment:
patient_id: integer
clinician_id: integer
created_at: datetime
updated_at: datetime
inputter_name: string
inputter_id: integer
class EsasAssessment < ActiveRecord::Base
belongs_to :other_symptom
belongs_to :clinician
belongs_to :patient
belongs_to :inputter
end
Inputter is:
Inputter:
inputter_type: string
class Inputter < ActiveRecord::Base
has_many :esas_assessments
end
When I submit my form I don't get any errors or warning, inputter_id is just nil
if I enter
Inputter.find_by(inputter_type: 'Medical team')
in Console it returns
#<Inputter {"id"=>309, "inputter_type"=>"Medical team"}>
Any advice on how to get the value to stick to the new EsasAssessment would be great
Ruby rails can't add user entry
Everything seems to go fine and there's no error message when executing user.save, but it doesn't show up when indexing.
I ran the migration:
class AddEmailToUsers < ActiveRecord::Migration
def change
add_column :email, :name, :password, :password_confirmation, :string
end
end
models/user.rb
class User < ActiveRecord::Base
#attr_accessor :remember_token
attr_accessor :email
attr_accessor :name
attr_accessor :password_digest
attr_accessor :password, :password_confirmation
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
# has_secure_password
validates :password, length: { minimum: 6 }
# functions...
end
Here on create I fill in some sample values to test it, and it submits to views/users/create.html.erb without anything displaying in "Error: []" and the correct data shown for the fields of @user.
controllers/user_controller.rb
class UsersController < ApplicationController
def new
#require 'bcrypt'
@user = User.new
end
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def create
#@user = User.new(user_params)
@user = User.new(name: "di3", email:"di3@di3.com", password: "di3", password_confirmation: "di3")
#@user = User.new(params[:user])
if @user.save!
log_in @user
flash[:success] = "Welcome to the forum!"
#redirect_to @user
#redirect_to users_path
else
#render 'new'
render @user.error_messages.full
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
end
views/users/create.html.erb
<h1>Create user params</h1>
<%= render partial: 'layouts/header' %>
<table>
<tr>
<th>Email</th>
<th>Name</th>
<th>Password</th>
</tr>
<tr>
<td><%= @user.email %></td>
<td><%= @user.name %></td>
<td><%= @user.password %></td>
<td><%= @user.password_confirmation %></td>
</tr>
</table>
<br/>
Error:
<%= @user.errors.full_messages %>
But this user index doesn't show any users at all:
views/users/index.html.erb
<h1>Listing forums</h1>
<%= render partial: 'layouts/header' %>
<table>
<tr>
<th>Email</th>
<th>Name</th>
<th>Password</th>
<th>Password</th>
<th>Password</th>
</tr>
<% if(@users)
@users.each do |user| %>
<tr>
<td><%= user.email %></td>
<td><%= user.name %></td>
<td><%= user.password_digest %></td>
<td><%= user.password %></td>
<td><%= user.password_confirmation %></td>
</tr>
<% end %>
<% end %>
</table>
Rails: Tips for parsing JSON [on hold]
I'm relatively new to rails. Was curious if I'm parsing JSON the 'right/best' way. So I'm trying to get a list of subreddits from Reddit so I used the subreddits JSON from Reddit.
Here is what I first did to convert the JSON to hash -
require 'open-uri'
hash = JSON.load(open('http://ift.tt/1k5Yusm'));
I then, got the list display_name (subreddit names) from my hash the following way -
subreddit_arr = hash["data"]["children"].map { |c| c["data"]["display_name"]}
which gave me -
["funny", "pics", "AdviceAnimals", "aww", "todayilearned", "videos", "gaming", "gifs", "BlackPeopleTwitter", "WTF", "fatpeoplehate", "leagueoflegends", "AskReddit", "pcmasterrace", "me_irl", "worldnews", "news", "Showerthoughts", "DotA2", "4chan", "mildlyinteresting", "TrollXChromosomes", "nba", "politics", "trees"]
How can I get a list of all subreddits (not just 25) in the most efficient manner?
Ruby / Brew Stopped Working Yosemite
I'm fairly new to this so hang with me..
I have been searching for a solution to this problem for a week now.
Ruby does not seem to be working
ruby
-bash: ruby: command not found
or
ruby -v
-bash: ruby: command not found
and whenever I try homebrew this is what comes back
/usr/local/bin/brew: /usr/local/Library/brew.rb: /System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby: bad interpreter: No such file or directory
/usr/local/bin/brew: line 21: /usr/local/Library/brew.rb: Undefined error: 0
as you can see above I had changed the ruby framework to read from 1.8 to Current as others had suggested, however this did not solve the problem as it did for users who had encountered the same issue.
So the search continues on...
My usr/local/bin/brew script looks like this -
#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby -W0
# encoding: UTF-8
std_trap = trap("INT") { exit! 130 } # no backtrace thanks
HOMEBREW_BREW_FILE = ENV['HOMEBREW_BREW_FILE']
if ARGV == %w{--prefix}
puts File.dirname(File.dirname(HOMEBREW_BREW_FILE))
exit 0
end
require 'pathname'
HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.dirname.parent.join("Library/Homebrew").to_s
$:.unshift(HOMEBREW_LIBRARY_PATH + '/vendor')
$:.unshift(HOMEBREW_LIBRARY_PATH)
require 'global'
case ARGV.first when '-h', '--help', '--usage', '-?', 'help', nil
require 'cmd/help'
puts Homebrew.help_s
exit ARGV.first ? 0 : 1
when '--version'
puts HOMEBREW_VERSION
exit 0
when '-v'
puts "Homebrew #{HOMEBREW_VERSION}"
# Shift the -v to the end of the parameter list
ARGV << ARGV.shift
# If no other arguments, just quit here.
exit 0 if ARGV.length == 1
end
# Check for bad xcode-select before anything else, because `doctor` and
# many other things will hang
# Note that this bug was fixed in 10.9
if OS.mac? && `xcode-select -print-path 2>/dev/null`.chomp == '/' && MacOS.version < :mavericks
ofail <<-EOS.undent
Your xcode-select path is currently set to '/'.
This causes the `xcrun` tool to hang, and can render Homebrew unusable.
If you are using Xcode, you should:
sudo xcode-select -switch /Applications/Xcode.app
Otherwise, you should:
sudo rm -rf /usr/share/xcode-select
EOS
exit 1
end
case HOMEBREW_PREFIX.to_s when '/', '/usr'
# it may work, but I only see pain this route and don't want to support it
abort "Cowardly refusing to continue at this prefix: #{HOMEBREW_PREFIX}"
end
if OS.mac? and MacOS.version < "10.5"
abort <<-EOABORT.undent
Homebrew requires Leopard or higher. For Tiger support, see:
http://ift.tt/17h053J
EOABORT
end
# Many Pathname operations use getwd when they shouldn't, and then throw
# odd exceptions. Reduce our support burden by showing a user-friendly error.
Dir.getwd rescue abort "The current working directory doesn't exist, cannot proceed."
def require? path
require path.to_s.chomp
rescue LoadError => e
# HACK :( because we should raise on syntax errors but
# not if the file doesn't exist. TODO make robust!
raise unless e.to_s.include? path
end
begin
trap("INT", std_trap) # restore default CTRL-C handler
aliases = {'ls' => 'list',
'homepage' => 'home',
'-S' => 'search',
'up' => 'update',
'ln' => 'link',
'instal' => 'install', # gem does the same
'rm' => 'uninstall',
'remove' => 'uninstall',
'configure' => 'diy',
'abv' => 'info',
'dr' => 'doctor',
'--repo' => '--repository',
'environment' => '--env',
'-c1' => '--config',
}
cmd = ARGV.shift
cmd = aliases[cmd] if aliases[cmd]
sudo_check = Set.new %w[ install link pin unpin upgrade ]
if sudo_check.include? cmd
if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero?
raise "Cowardly refusing to `sudo brew #{cmd}`\n#{SUDO_BAD_ERRMSG}"
end
end
# Add contributed commands to PATH before checking.
ENV['PATH'] += ":#{HOMEBREW_CONTRIB}/cmd"
if require? HOMEBREW_REPOSITORY/"Library/Homebrew/cmd"/cmd
Homebrew.send cmd.to_s.gsub('-', '_').downcase
elsif which "brew-#{cmd}"
%w[CACHE CELLAR LIBRARY_PATH PREFIX REPOSITORY].each do |e|
ENV["HOMEBREW_#{e}"] = Object.const_get "HOMEBREW_#{e}"
end
exec "brew-#{cmd}", *ARGV
elsif require? which("brew-#{cmd}.rb").to_s
exit 0
else
onoe "Unknown command: #{cmd}"
exit 1
end
rescue FormulaUnspecifiedError
abort "This command requires a formula argument"
rescue KegUnspecifiedError
abort "This command requires a keg argument"
rescue UsageError
onoe "Invalid usage"
abort ARGV.usage
rescue SystemExit
puts "Kernel.exit" if ARGV.verbose?
raise
rescue Interrupt => e
puts # seemingly a newline is typical
exit 130
rescue BuildError => e
e.dump
exit 1
rescue RuntimeError, SystemCallError => e
raise if e.message.empty?
onoe e
puts e.backtrace if ARGV.debug?
exit 1
rescue Exception => e
onoe e
puts "#{Tty.white}Please report this bug:"
puts " #{Tty.em}#{ISSUES_URL}#{Tty.reset}"
puts e.backtrace
exit 1
else
exit 1 if Homebrew.failed?
end
enter code here
Does any of this make sense or ring any bells? Could it have anything to do with why I'm getting the Homebrew or Ruby error?
Any help would be greatly appreciated.
I'd be happy to provide as much information as possible for us to solve this problem! :)
ruby idiom for update or insert a hashmap
Is there a common ruby idiom for this code:
if hashmap.has_key?(key)
hashmap[key] += 1
else
hashmap[key] = 1
end
It feels like there might be a high order function that helps here. I'm hoping for something like
hashmap[key].insertOrUpdate { 1 }, {|value| value += 1}
How to combine two same blocks into a single one?
How can I use a single block in this:
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:full_name, :email, :password, :password_confirmation)
end
devise_parameter_sanitizer.for(:account_update) do |u|
u.permit(:full_name, :email, :password, :password_confirmation)
end
Counting the Days from the current_level?
There are 5 levels.
Each level has a certain amount of days in it that must pass before the habit can move up to the next level (as broken down by n_days):
case n_days
when 0..9
1
when 10..24
2
when 25..44
3 #Level 3
when 45..69
4
when 70..99
5
else
"Mastery"
end
end
How can we call the n_days from the present level in the habits index with something like <%= habit.current_level.n_days.count_off_from_zero_to_show %>?
For example, if we are specifically at 50 on level 3 it would show Day 5 in the habits index.
habit.rb
class Habit < ActiveRecord::Base
belongs_to :user
has_many :comments, as: :commentable
has_many :levels
serialize :committed, Array
validates :date_started, presence: true
before_save :current_level
acts_as_taggable
scope :private_submit, -> { where(private_submit: true) }
scope :public_submit, -> { where(private_submit: false) }
attr_accessor :missed_one, :missed_two, :missed_three
def save_with_current_level
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.levels.build
self.save
end
def self.committed_for_today
today_name = Date::DAYNAMES[Date.today.wday].downcase
ids = all.select { |h| h.committed.include? today_name }.map(&:id)
where(id: ids)
end
def current_level_strike
levels[current_level - 1] # remember arrays indexes start at 0
end
def current_level
return 0 unless date_started
committed_wdays = committed.map { |day| Date::DAYNAMES.index(day.titleize) }
n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday } - self.missed_days
case n_days
when 0..9
1
when 10..24
2
when 25..44
3
when 45..69
4
when 70..99
5
else
"Mastery"
end
end
end
level.rb
class Level < ActiveRecord::Base
belongs_to :habit
end
schema
create_table "habits", force: true do |t|
t.integer "missed_days", default: 0
t.text "committed"
t.integer "days_lost", default: 0
t.datetime "date_started"
t.string "trigger"
t.string "target"
t.string "reward"
t.boolean "private_submit"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "order"
end
add_index "habits", ["user_id", "created_at"], name: "index_habits_on_user_id_and_created_at"
add_index "habits", ["user_id"], name: "index_habits_on_user_id"
create_table "levels", force: true do |t|
t.integer "habit_id"
t.integer "days_lost", default: 0
t.integer "missed_days", default: 0
t.integer "current_level"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "levels", ["habit_id"], name: "index_levels_on_habit_id"
The Gist of it: http://ift.tt/1PISTF0
NoMethodError in Blog::PostsController#create
Note: Rails newb here.
So, I recently created a Rails app with mongoid gem for use of MongoDB. I have a namespace route of :blog with a nest of resource of posts
Routes.rb:
Rails.application.routes.draw do
namespace :blog do
resources :posts
end
end
The error comes from app/controllers/blog/post_controller.rb:
Class Blog::PostController < ApplicationController
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
end
I also have a 'post' model that comes with a title and body:
Class Post
include Mongoid::Document
field :title, type: String
field :body, type: String
end
In new.html.erb:
<h1>Rails Sample Blog</h1>
<%= form_for :post, url: blog_post_path do |f| %>
<div><%= f.label :title %><%= f.text_field :title %></div>
<div><%= f.label :body %><%= f.text_area :body %></div>
<% end %>
Is there something I left out that I didn't catch? It's slowly haunting me.
Multidimensional Arrays in Ruby like C++
I had previously created a struct and an array of the same in C++ , now i want to implement the same in Ruby.
/ Number of Elements (Which can be increased) :D
#define ELM_NO 110
struct elem
{
char name[18];
char elm_symbol[5];
double atm_weight;
int elm_melting;
int elm_boiling;
int elm_yearofdis;
int elm_group;
double elm_ionis_e;
};
elem element[ELM_NO] = { {" Hydrogen" ,"H" ,1.0079 ,-259 ,-253 ,1776 ,1 ,13.5984 },
{" Hydrogen" ,"H" ,1.0079 ,-259 ,-253 ,1776 ,1 ,13.5984 } ,
{" Helium" ,"He" ,4.0026 ,-272 ,-269 ,1895 ,18 ,24.5874 } ,
{" Lithium" ,"Li" ,6.941 ,180 ,1347 ,1817 ,1 ,5.3917 } ,
{" Beryllium" ,"Be" ,9.0122 ,1278 ,2970 ,1797 ,2 ,9.3227 } ,
{" Boron" ,"B" ,10.811 ,2300 ,2550 ,1808 ,13 ,8.298 } ,
{" Carbon" ,"C" ,12.0107 ,3500 ,4827 ,0 ,14 ,11.2603 } ,
{" Nitrogen" ,"N" ,14.0067 ,-210 ,-196 ,1772 ,15 ,14.5341 } ,
{" Oxygen" ,"O" ,15.9994 ,-218 ,-183 ,1774 ,16 ,13.6181 } ,
{" Fluorine" ,"F" ,18.9984 ,-220 ,188 ,1886 ,17 ,17.4228 } ,
{" Neon" ,"Ne" ,20.1797 ,-249 ,-246 ,1898 ,18 ,21.5645 } ,
{" Sodium" ,"Na" ,22.9897 ,98 ,883 ,1807 ,1 ,5.1391 } ,
{" Magnesium" ,"Mg" ,24.305 ,639 ,1090 ,1755 ,2 ,7.6462 } ,
{" Aluminum" ,"Al" ,26.9815 ,660 ,2467 ,1825 ,13 ,5.9858 } };
Omitted some parts.
Now , I want to implement in Ruby . The problem is I don't know how to implement 2D arrays from which we can access an Individual Element from the Inner Array.
Can anybody show me how it's done ?
Convert sample java code to ruby to understand static variales in ruby
can anybody help me to convert this simple java code to ruby.
class A {
private static String[] chachedNames;
public static String[] getNames(){
if(chachedNames == null)
chachedNames = prepareNames(); //This process will take 20sec to complete
return chachedNames;
}
}
I'm trying to understand basic memory caching on static method. How do implement same on Ruby.
Getting date parts from a simple treetop parser: wrong argument type Class (expected Module)
For the following treetop grammer, when parsing '3/14/01' (via t = Parser.parse('3/14/01') in irb), I get a "TypeError: wrong argument type Class (expected Module)".
grammar SimpleDate
rule dateMDY
whitespace? month_part ( '/' / '-') day_part ( ('/' / '-') year_part)? whitespace? <DateMDY>
end
rule month_part
( ( '1' [0-2] ) / ( '0'? [1-9] ) ) <MonthLiteral>
end
rule day_part
( ( [12] [0-9] ) / ( '3' [0-1] ) / ( '0'? [1-9] ) ) <DayLiteral>
end
rule year_part
( ( '1' '9' ) / ( '2' [01] ) )? [0-9] [0-9] <YearLiteral> # 1900 through 2199 (4 digit)
end
rule whitespace
[\s]+
end
end
First, if I comment out the <MonthLiteral> and the <DayLiteral> class references, all is well. Commenting out <DateMDY>, but leaving those Literal objects in, will also issue the error. Commenting out <YearLiteral> does not seem to matter (it'll work or not work regardless) -- that seems to indicate that because the first two are non-terminal, I can't produce elements for them.
There is clearly something I'm not appreciating about how Ruby (or treetop) is instantiating these classes or about AST generation that would explain what happens. Can you explain or point me to something that can help me understand why <MonthLiteral> or <DayLiteral> can't have objects generated?
Second, this may be a bridge too far, but what I'd really prefer would be to get a DateMDY object with three attributes -- month, day, and year -- so I can readily produce a Ruby Time object from a method to_time in DateMDY, but right now I'd settle for just producing the constituent pieces as objects.
So I tried leaving <DateMDY> as the object and commented out the references to <MonthLiteral>, <DayLiteral>, and <YearLiteral>. I saw that the resulting AST object returned from .parse (t in my original example) has two public methods -- :day_part and :month_part but those seem to be nil when I invoke those (say, puts t.day_part) and there is no :year_part method, so that didn't seem to help me out.
Is it possible to do somehow have DateMDY end up accessing its constituent parts?
FYI, the Parser code itself I'm using is pretty standard stuff from the treetop tutorials and the node_extensions.rb that defines the object classes is also trivial, but I can post those too if you need to see those.
Thanks! Richard
Rename everything to match new inflection after running a generator
I have a model in my rails app that has an irregular pluralisation. I know that I can fix this by adding the appropriate code to config/initializers/inflections.rb.
The problem is I didn't realise it was incorrect until after I ran a bunch of other generators and wrote a lot of code.
Is there any easy way (perhaps a gem?) to batch rename all my files, models, controllers, schema (via a migration I guess), etc to use the correct inflection?
How to reimplement the map method in ruby using recursion?
I'm a ruby newbie, learning to code. I wanted to understand how some of the methods available from the Enumerable module work. So I'm reimplementing them. One challenge was to implement them using recursion. However, I'm running into a problem when trying to implement the Enumerable#Map method using recursion.
This is my code:
class Array
def mymap_recursive(&block)
copy_of_array = dup
new_array = []
return new_array if copy_of_array.empty?
value = copy_of_array.shift
new_array << yield(value)
copy_of_array.mymap_recursive(&block)
end
end
I tried to figure out why it wasn't working so I put
puts "#{new_array}"
at the end of the method. Then in Sublime Text, I did
arr = [2,2,5,5,10]
arr.mymap_recursive {|n| n * n}
After pressing cmd+b, the output I got was:
[100]
[25]
[25]
[4]
[4]
I cannot figure out why its not returning one array with all the values.
Thanks for your help!
What's the best way search a Ruby Hash for key-value pairs matching a value and then changing that value?
I'm building a Blackjack game to better understand Ruby, and am trying to have users able to switch out values from a "hand." I store the deck as a Hash containing the deck and then scoring value like this :D8 => 8 where it's an eight of Diamonds worth eight points. Aces, because they can be either 1 or 11 get stored like this: :SA => "option."
I would like to be able to prompt the user to for a value or This is currently part of the code:
def checkAce
if @player_hand.has_value?("option")
puts "What do you want your aces to be worth? 11 or 1"
ace_value = gets.chomp
aces = @player_hand.find {|k, v| @player_hand[k] == "option"}
if ace_value == "1" || ace_value == "11"
aces.each { |k, v| aces[k] = ace_value }
else
checkAce
end
# merge back into hand
@player_hand.merge!(aces)
else
puts "No aces, so on to the main event."
end
end
But this code doesn't work: first, the ace_value gives me a typeerror saying that symbol cannot be coerced into integer. And second, the @player_hand.merge!(aces) doesn't find a method. Any advice?
Testing infinite loop with MiniTest and using mocking
I have a section in my code which polls a queue for a message and then acts on it depending on the message type:
@queue = Foo::Queue.new
loop do
@queue.poll do |message|
if message[:task] == TAKEACTION
result = takeaction(message)
@queue.send_result(result, message)
end
@queue.pong(message) if message[:task] == PING
end
end
How do I set up a test to supply a single message and verify that the @queue acts on it as I expect?
I have seen very little about testing blocks in minitest, and haven't found anything in ruby regarding breaking out of infinite loops, though I found one idea in python where you set up the second run to throw an exception.
Can any ruby / minitest gurus help?
Error when ruby install on windows xp sp3 32 bit
I am trying to install and run Ruby on Windows XP sp3 32bit, and running into issues.
- I downloaded the file
ruby2.2.2.exefrom the ruby installer website and installed it. -
When I tried to execute Ruby through the command prompt
cmd, I got the following error:The procedure entry point_gmtime64_s could not be located in the dynamic link >library msvcrt.dll.
Please help me resolve it! :)
Ruby method using class and instances
I'm just starting out with Ruby and trying to write a method that returns "Title was written by author", where title and author are variables. I think I'm close, but I'm not sure what to add at this point.
class Book
def set_title_and_author=(title, author)
@title = title
@author = author
end
def set_title_and_author
"#{@title} was written by #{@author}"
end
end
Creating user from rails console command?
I am newbie in Ruby, I am trying to install one app that says:
lobsters$ rails console
Loading development environment (Rails 4.1.8)
irb(main):001:0> User.create(:username => "test", :email => "test@example.com", :password => "test", :password_confirmation => "test", :is_admin => true, :is_moderator => true
irb(main):002:0> Tag.create(:tag => "test")
When I run rails console, it outputs "create some file" So how do I create user?
Group by date and reduce an array to create a new one
I have this array:
> source
# =>
[[Fri, 13 Mar 2015, [24.2]],
[Tue, 17 Mar 2015, [0.01, 8.26]],
[Mon, 16 Mar 2015, [0.01, 0.01, 0.01, 0.01]],
[Mon, 16 Mar 2015, [0.01, 0.01]],
[Fri, 13 Mar 2015, [24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2]],
[Fri, 13 Mar 2015, [24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2]],
[Mon, 16 Mar 2015, [15.95]],
[Thu, 12 Mar 2015, [352429.0, 35242900.0, 3.0]]
]
How can I create this one out of it:
[
[Thu, 12 Mar 2015, aaa]
[Fri, 13 Mar 2015, bbb],
[Mon, 16 Mar 2015, ccc],
[Tue, 17 Mar 2015, ddd]
]
Where aaa, bbb ... are the sums of the elements with the same date. Note that [Thu, 12 Mar 2015, aaa]
are 2 elements, not 3: 12 Mar 2015 and aaa
What I tried:
source.group_by { |x| x[0] }.reduce(0) # sum up all the element except the 1st one which is a date - how?
What's happens in Ruby and Python? Why the variable wil be nil in if block in ruby ,but undefined in python?
This question already has an answer Confusion with the assignment operation inside a falsy `if` block
if false
y = 'hi'
end
puts y
In ruby y has been "defined" in the if block,it will be nil(why?). Remove that block and this gives an error.
But, in python
if False:
y = 'hi'
print y
It will gives an error.
What's happens in Ruby and Python?
Getting user ID when calling an action
I have a table for doing CRUD operations on books, and also users can check in books (the checking out is done my a different controller)
At the moment the check in works for the book table, but I can't update user data - the integer of how many books they have loaned out
Here is part of my table:
<tr><% @books.each do |book| %>
<td><%= book.title %></td>
<td><%= book.author %></td>
<td class ="onloan"><%= book.onloan %></td>
<td><%= link_to 'show', book %> </td>
<td><%= link_to 'edit', edit_book_path(book) %></td>
<td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'Check in', check_in_path(book)%></td>
</tr>
<% end %>
What I want to add is something like
@user = User.find(params[:id])
@user.books_on_loan - 1
Here is the check in def of my controller:
def check_in
Book.find(params[:id]).update_attribute(:onloan, 0)
redirect_to root_path
end
extract info out of XML tag - RUBY
I have an xml tag like this
<cvParam cvRef="MS" accession="MS:1000511" name="ms level" value="1"/>
How can i get the value of ms level (1)? Please, don't suggest nokogiri or rexml. I want to learn how I can parse info out while I read the file, line by line. Thank you.
Avoiding eval when building radio buttons in rails
Here, I am building database driven radio buttons. I wanted to know if there is a way I can avoid eval and see checked is true or not !Thanks,
Index Controller
columns = Model.column_names
View in haml
- columns.each do |cols|
- check = "c[0].#{cols}==1? true : false" // checking value here
- negcheck = "c[0].#{cols}==0? true : false"// checking value here
- pluckid = "c[0].id"
- id = eval(pluckid)
%tbody
%td #{cols}
%td
= label_tag 'On'
= radio_button_tag("ABC",1,checked = eval(check), options = {})
= label_tag 'Off'
= radio_button_tag("xyz",0,checked = eval(negcheck), options = {})
Return from multiple ruby forks
I have the following code
read, write = IO.pipe
count = {}
ARGV.each do |filename|
fork do
read.close
write.write Marshal.dump(do_stuff(filename))
write.close
end
end
write.close
count = Marshal.load(read.read)
read.close
Process.waitall
printf(count)
which works for one fork but I obviously want to achieve concurrency so I'd need to get the count hash from all the forks. However I've so far only been able to retrieve one hash from either of the forks. How can I return all of them?