In our rails 6 project I want to upload excel file into S3 bucket and send file link to email and provide download xls feature from email. Please help me.
jeudi 30 avril 2020
mercredi 29 avril 2020
Localhost:3000 is not working for Ruby on Rails on windows
Hi I'm new to ruby and my localhost:3000 is not working on my windows machine enter image description here
I did exactly the way the guy has done in this video But it worked his this machine whereas mine did not and then I tried many different ways that I got on the internet ut it all proved to be a waste of time. Please help me!! I'm stuck with this from like last 5 days and haven't made any progress
mardi 28 avril 2020
Parsing multiple .log files to get a string name
File1.log Result for scripts as follows {"Script 1"=>{"expected"=>"Pass", "actual"=>"Pass", "result"=>true},
"Script 2"=>{"expected"=>"Fail", "actual"=>"Pass", "result"=>false}
-----
Result for scripts as follows {"Script 3"=>{"expected"=>"Pass", "actual"=>"Pass", "result"=>true}, "Script 4"=>{"expected"=>"Fail", "actual"=>"Pass", "result"=>false}
File2.log Result for scripts as follows {"Script 1"=>{"expected"=>"Pass", "actual"=>"Pass", "result"=>true}, "Script 2"=>{"expected"=>"Pass", "actual"=>"Pass", "result"=>true}
I will have to parse the .log files which will contain multiple lines and get the above given lines alone.
The only thing common to be used to get this is the first text : "Result for scripts as follows" .
Any suggestions to solve this using Ruby or any powershell commandsRU
lundi 27 avril 2020
how to pass the return value of function with & operator in ruby?
I came across following code snippet in ruby, where the safe navigation operator is used to call a second method, in the example below, does the response we get from Excon.get call passed to the process_json automatically. in the function definition of process_json ,there is no parameter being passed. I am not sure how this might work.
class Client
API_ENDPOINT = 'https://api.twitter.com'
class << self
def call()
Excon.get(API_ENDPOINT)&.process_json
end
def process_json
//process json response
end
end
end
confirmation token Automatically generated NIL
Hello guys, I have an issue with automatically generated token. In a model, i generate token automatically like this:
class User < ApplicationRecord
before_create :generate_confirm_token
def generate_confirm_token
self.confirm_token = generate_token
end
def generate_token
loop do
token = SecureRandom.hex(10)
break token unless User.where(confirm_token: token).exists?
end
end
That works fine for me, after creating of user, the token is generated. But the issue is in a Controller:
class Companies::StudentsController < ApplicationController
def create
@company = Company.find(params[:company_id])
@student = @company.students.create(student_params)
raise @student.inspect
if @student.save
StudentMailer.with(student: @student).welcome_email.deliver_now
redirect_to company_students_path
else
render :new
end
end
Object student, contains confirm_token BUT in a params, the confirm token is empty!
I need the token in params because in next step (mailer) i use Find_by(params[:confirm_token]) Here is how use a confirm_token in my view (i assume i need the confirm_token in params so i have to have it in a view also):
<%= f.hidden_field :confirm_token %>
I dont know how to solve it, but I think i need a token value in a params - but how to put the value there? Thank you!
dimanche 26 avril 2020
How to write if statement in table
I'm trying to write an if statement in a table to get one image if an image doesn't exist in the database. Im able to retrieve both images separately but not with the if statement. What am I doing wrong in my code.
<h1>Won Auctions</h1>
<br>
<table class= "table table-hover" >
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>End Date</th>
<th>Seller</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% won.each do |a| %>
<tr>
<td><%=
if a.image.exists? %>
<% image_tag(a.image, width:100) %>
else
<% image_tag("No_image.jpg", width:100) %>
<% end %>
%><td>
<td><%= a.name %></td>
<td><%= number_to_currency(a.highest_bid) %></td>
<td><%= a.auction_end_time %></td>
<td><%= a.seller.email %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
Why psql can not connect to server?
When I run the command Rails s and refresh http://localhost:3000/ . I get the following error :
Internal Server Error
could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
WEBrick/1.6.0 (Ruby/2.7.1/2020-03-31) at localhost:3000
I have tried every possible solution given on StackOverflow. it isn't working for me .
I am using Rails on Bash in Ubuntu for Windows.Here are the versions : Rails 4.2.10 Ruby 2.7.1p83 railties-4.2.10
samedi 25 avril 2020
Rails application reads a stale record
Consider the following situation. I have two machines (AWS EC2s), A and B. A and B have access to a common database. I also have a single DB table MyTable which has a single record with fields field1
, field2
, field3
.
On A I have a pure Ruby script which once a minute updates the fields (using pg gem). On B I have a Rails 5 application which reads field1
, field2
, field3
.
Now, the wired thing is that even after the Ruby script updates the field values, the Rails application still reads the old (stale?) values of the fields. I read the record as following
def myRecord
rec ||= MyTable.first
end
If I restart the Rails application it reads the correct (latest) value. I guess this is because the Rail application reads from cache. Please correct me if I.m wrong. So, how could I force the Rails application to read the most recent value from the database?
vendredi 24 avril 2020
Getting Cookie Overflow in rails application(REDMINE)
ActionDispatch::Cookies::CookieOverflow (ActionDispatch::Cookies::CookieOverflow):
actionpack (4.2.8) lib/action_dispatch/middleware/cookies.rb:529:in `[]='
I am getting this error when hitting redmine rest api. The simple get api like url1 works fine but when it come to complex url as url2 the application throws cookie overflow.
url1: localhost:3000/issues.json?page=1&limit=100
url2: https://deerminetest.deerwalk.com/issues.json?key=292fe116d13d5f5db8a0e3f2b031f1e57ad1c882&f[]=project_id&op[project_id]=!&v[project_id][]=505&f[]=project_id&op[project_id]=!&v[project_id][]=478&f[]=project_id&op[project_id]=!&v[project_id][]=366&f[]=project_id&op[project_id]=!&v[project_id][]=419&f[]=project_id&op[project_id]=!&v[project_id][]=343&f[]=project_id&op[project_id]=!&v[project_id][]=345&f[]=project_id&op[project_id]=!&v[project_id][]=512&f[]=project_id&op[project_id]=!&v[project_id][]=487&f[]=project_id&op[project_id]=!&v[project_id][]=473&f[]=project_id&op[project_id]=!&v[project_id][]=509&f[]=project_id&op[project_id]=!&v[project_id][]=520&f[]=project_id&op[project_id]=!&v[project_id][]=404&f[]=project_id&op[project_id]=!&v[project_id][]=440&f[]=project_id&op[project_id]=!&v[project_id][]=389&f[]=project_id&op[project_id]=!&v[project_id][]=467&f[]=project_id&op[project_id]=!&v[project_id][]=501&f[]=project_id&op[project_id]=!&v[project_id][]=474&f[]=project_id&op[project_id]=!&v[project_id][]=471&f[]=project_id&op[project_id]=!&v[project_id][]=480&f[]=project_id&op[project_id]=!&v[project_id][]=507&f[]=project_id&op[project_id]=!&v[project_id][]=383&f[]=project_id&page=1&limit=100
I have not stored anything but username, cas ticket in session as:
request.session['cas'] = { 'user' => user, 'ticket' => ticket, 'extra_attributes' => [] }
I have searched for the solution in many forums. All said donot save unnecessary data but all i am saving are username and cas ticket. When i print session this is the result:
puts(session.to_hash)
{"session_id"=>"fbe61cf9fd1c2ef0111d5d84a1a374c2", "cas"=>{"user"=>"user@gmail.com", "ticket"=>"ST-27189-R20MW7GBWaLWNJvl1aMi-localhost", "extra_attributes"=>[]}}
But when inspect session as below i get loads of gibberish data like below:
puts(session.inspect)
[result]: https://textsaver.flap.tv/lists/3caw "Click here for session.inspect output"
Since i am a newbie and just starting ruby on rails any suggestions will be highly appreciated. Thank You.
'joins' queries are not working on upgrading ruby from 2.0.0 to 2.3.8
I have just updated the ruby version of my project from ruby-2.0.0 to ruby-2.3.8. Now after update there seems to be a problem while using joins in rails and I am not getting why. Here is the code below.
class User < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :user
has_many :donors, :as => :itemable, :dependent => :destroy
end
u = User.find_by_id(15)
u.items.joins(:donors)
it is returning me a Module object like '#<#Module<:0x00000000088932f0>:0x44497e8>', which is inaccessible
but the same thing when I do in my previous ruby version before updating
it gave me the ActiveRecord:: Relation object as expected
I am not getting the problem so if anybody can suggest something.
mardi 21 avril 2020
How can I find date of file in ruby. And how can I print all the files which are less than a given time?
I want to iterate through all the files which were created before 3 months.
dimanche 19 avril 2020
assert_select count expected exactly 2 elements matching “a[href=”/“]”, found 3
I'm trying to check how many links are routed to root_path
. but it keeps giving 3. I tried to take out all root_path
, check if I miss spelled anything but it looked fine for me.
Here is my code for all the needed pages
IntegrationTest
require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
test "layout links" do
get root_url
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path, count: 2
assert_select "a[href=?]", help_path, count: 1
assert_select "a[href=?]", about_path, count: 1
assert_select "a[href=?]", contact_path, count: 1
end
end
_header
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<%= link_to "sample app", root_path, id: "logo" %>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Help", help_path %></li>
<li><%= link_to "Log in", '#' %></li>
</ul>
</nav>
</div>
</header>
_footer.html.erb
<footer class="footer">
<small>
The <a href="https://www.railstutorial.org/">Ruby on Rails Tutorial</a>
by <a href="https://www.michaelhartl.com/">Michael Hartl</a>
</small>
<nav>
<ul>
<li><%= link_to "About", about_path %></li>
<li><%= link_to "Contact", contact_path %></li>
<li><a href="https://news.railstutorial.org/">News</a></li>
</ul>
</nav>
</footer>
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= render 'layouts/rails_default' %>
<%= render 'layouts/shim' %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
<%= render 'layouts/footer' %>
</div>
</body>
</html>
routes.rb
Rails.application.routes.draw do
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
end
samedi 18 avril 2020
Rails - How to avoid inserting the html in method
I have a method in my project to show the title of books and a followed icon in the table. The method is:
def title_and_follow()
"#{h.link_to object.title, h.show_book_path(object.uuid)}
#{h.follow_icon(user, object)}".html_safe
end
It works fine and it shows something like "Harry Potter [followed_icon]" in my table. However, I wonder is there any way to avoid inserting HTML directly in the method? Is there a more elegant way to do that?
How can I insert and variable in between 2 strings in ruby on rails
My code:
@pageb=2
<a data-remote="true" href="/?activities_page= @pageb &partial=true&render=activities"> >> </a>
URL I want:
http://localhost:9292/?activities_page= 2 &partial=true&render=activities
URL I get:
http://localhost:9292/?activities_page= %20@pageb%20 &partial=true&render=activities
mercredi 15 avril 2020
How to customize Jenkins to show only failed cucumber features from different pipelines at one place?
I have my Jenkins setup which has 10 cucumber Pipelines together, how can i customize Jenkins to show me all the failed features from all the 10 pipelines at a shot instead me going to individual pipelines
RSpec - how to check if the inside method been called
I got a method to update the person by id:
def update_person(id)
handle_exceptions do
person = Person.find(id)
#...other
end
end
When this id doesn't exist, the handle_exception should be called. But how could I test it? The test I wrote is:
context 'not found the proposals' do
subject {controller.send(:update_person, 3)}
before do
allow(Person).to receive(:find).and_raise(ActiveRecord::RecordNotFound)
allow(subject).to receive(:handle_exceptions)
end
it 'calls handle_exceptions' do
expect(subject).to have_received(:handle_exceptions)
end
end
But it not works, I got a failure said: Failure/Error: expect(subject).to have_received(:handle_exceptions)
({:message=>"Not Found", :status=>:not_found}).handle_exceptions(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
How to set the env variable temporarly under a API context
I want to set up some env variable and it needs to be present in that variable only when an API is called. After the API call, the ENV variable should get the default value
While testing test helper method is not called, other method is called
In testing rails , i am testing a controller, controller have a function which was from one helper , now while testing i need to use a function from test helper in that place , but it is calling the usual function though i have a function with same name in test_helper
mardi 14 avril 2020
has_many through create joint table with attributes
In my Rails app there are 3 model:
class Person < ApplicationRecord
has_many :roles
has_many :companies, through: :roles
end
class Company < ApplicationRecord
has_many :roles
has_many :people, through: :roles
end
class Role < ApplicationRecord
belongs_to :person
belongs_to :company
end
In console I'm able to create a joint table (Roles) with person_id and company_id, however I as well have job_title field I want to pass value during creation.
That's how I create joint table:
person = Person.find(id)
person.companies.create(legal_name: "Company name Ltd.")
As a result I get:
#<Role id: 1, person_id: 2, company_id: 25, job_title: nil>
Job title is nil and I want to populate this attribute with data during creation.
How I do something like this?
person = Person.find(id)
person.companies.create(legal_name: "Company name Ltd.", roles: [job_title: "Job title"])
lundi 13 avril 2020
How to use SendGrid to send email in Rails
I have a problem with SendGrid and Rails where my email do not arrive.
user_mailer.rb:
class UserMailer < ApplicationMailer
default from: 'xxxxxxxxxx@gmail.com'
layout 'mailer'
def daily_products(user, products)
@user = user
@products = products
mail(to: @user.email, subject: "Los productos top de ayer")
end
end
View daily_products.html.erb:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
</head>
<body>
<p>Hola,</p>
<p>Estos fueron los productos más votados el dia de ayer:</p>
<ol>
<% @products.each do |product| %>
<li><%= link_to product.name, product_url(product) %>: <%= product.description %></li>
<% end %>
</ol>
<p>Esperamos que tengas un dia lleno de productos digitales</p>
</body>
</html>
tasks/email.rake:
namespace :email do
desc "Sends the most voted products created yesterday"
task daily_products: :environment do
UserMailer.daily_products(User.first, Product.all).deliver_now
end
end
config/initializers/SendGrip.rb:
ActionMailer::Base.smtp_settings = {
address: 'smtp.sendgrid.net',
port: 467,
domain: ENV['HOSTNAME'],
user_name: ENV['SMTP_USER_NAME'],
password: ENV['SMTP_API_KEY'],
authentication: 'plain',
enable_starttls_auto: true
}
ActionMailer::Base.default_url_options[:host] = ENV["HOSTNAME"]
When I make a test it runs, however email is not arriving in the email accounts and SendGrid log doesn't show any error.
I don't know if theres any error in some configuration file, I have tried with many tutorials but the mistake persist.
Drop down in link_to button Rails
I've a view page Of student portal and i have certain buttons on the page in which i've defined action and controller , and now i want to give a dropdown view with these buttons and define action in them.
.pull-right
#average_mark
= link_to("Average Mark", {:controller => "student", :action => "average_marks", :academic_year => detail[:year]}, class:'btn btn-primary')
.pull-right
#highest_mark
= link_to("Highest Mark", {:controller => "student", :action => "highest_marks", :academic_year => detail[:year]}, class:'btn btn-primary')
what is the regular expression get initial from string word in all language like chinese, arabic, cyrillic, hindi in Ruby
Currently I am using scan(/(\A\w|(?<=\s)\w)/)
regular expression to get the initials from string word
Example str = "Sonu Singh"
str.scan(/(\A\w|(?<=\s)\w)/).flatten.join # output is "SS"
But this regexp
is not working for other language like Cyrillic character, arabic, chinese, hindi etc. Can anyone help me to make signle regexp
and get desired results.
Thank you so much any help or suggestion in any language.
dimanche 12 avril 2020
How can I do a before_action to redirect if you're signed in but not a member of the account
I am trying to create a before_action in my controller so only members (users) on an account can see and edit content related to an account. At the moment if I change the URL on the browser I can see and edit accounts that a user is not a member.
This is my discussion_controller:
class DiscussionsController < ApplicationController
before_action :set_discussion, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /discussions
def index
@newactivitys = Newactivity.all.order(created_at: :desc).limit(6)
@pagy, @discussions = pagy(Discussion.joins(:posts).group('discussions.id').order('MAX(posts.created_at) DESC'))
end
# GET /discussions/1
def show
@newactivitys = Newactivity.all.order(created_at: :desc).limit(6)
end
# GET /discussions/new
def new
@discussion = Discussion.new
@discussion.posts.new
@newactivitys = Newactivity.all.order(created_at: :desc).limit(6)
end
# GET /discussions/1/edit
def edit
@newactivitys = Newactivity.all.order(created_at: :desc).limit(6)
end
# POST /discussions
def create
@newactivitys = Newactivity.all.order(created_at: :desc).limit(6)
@discussion = Discussion.new(discussion_params)
@discussion.posts.each{ |post| post.user = current_user }
if @discussion.save
redirect_to @discussion, notice: 'Discussion was successfully created.'
else
render :new
end
end
# PATCH/PUT /discussions/1
def update
if @discussion.update(discussion_params)
redirect_to @discussion, notice: 'Discussion was successfully updated.'
else
render :edit
end
end
# DELETE /discussions/1
def destroy
@discussion.destroy
redirect_to discussions_url, notice: 'Discussion was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_discussion
@discussion = current_account.discussions.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def discussion_params
params.require(:discussion).permit(:account_id, :user_id, :channel_id, :channel_name, :title, posts_attributes: [:body])
end
end
and my models: User
class User < ApplicationRecord
include ActionText::Attachable
# Include default devise modules. Others available are:
# :lockable, :timeoutable, andle :trackable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:confirmable, :invitable, :masqueradable,
:omniauthable
include UserAgreements, UserAccounts
has_person_name
include PgSearch::Model
pg_search_scope :search_by_full_name, against: [:first_name, :last_name], using: { tsearch: { prefix: true } }
# ActiveStorage Associations
has_one_attached :avatar
# Associations
has_many :api_tokens, dependent: :destroy
has_many :connected_accounts, dependent: :destroy
has_many :discussions
has_many :posts
has_many :channels
has_many :newactivitys, foreign_key: :recipient_id
# We don't need users to confirm their email address on create,
# just when they change it
before_create :skip_confirmation!
# Validations
validates :name, presence: true
end
Discussion:
class Discussion < ApplicationRecord
acts_as_tenant :account
belongs_to :account
has_many :posts, dependent: :destroy
has_many :users, through: :posts
belongs_to :channel
scope :sorted, ->{ order(updated_at: :desc) }
validates :title, presence: true
accepts_nested_attributes_for :posts
end
And account:
class Account < ApplicationRecord
include Pay::Billable
belongs_to :owner, class_name: "User"
has_many :account_invitations, dependent: :destroy
has_many :account_users, dependent: :destroy
has_many :users, through: :account_users
has_one_attached :logo
scope :personal, ->{ where(personal: true) }
scope :impersonal, ->{ where(personal: false) }
has_one_attached :avatar
validates :name, presence: true
def email
account_users.includes(:user).order(created_at: :asc).first.user.email
end
def personal_account_for?(user)
personal? && owner_id == user.id
end
end
Thank you!
samedi 11 avril 2020
Can i recall the "case" in case?
I want to recall the case until user writes a or b. I do not want to use "case" particularly. I just want to get input from user but not geting something else. If he writes something else he should need to write until he writes a or b.
str = gets.chomp.to_s
case str
when "a"
print "nice a"
when "b"
puts "nice b"
else
puts "please do it again"
end
vendredi 10 avril 2020
Broken ruby on Mac when dealing with cocoapods
I'm trying to install a Cocoapods plugin and my Mac's gem and Ruby seem completely broken.
Here's my output for 'pod install':
[project] pod install master ✗ ✭
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /Library/Ruby/Gems/2.3.0/specifications/fuzzy_match-2.0.4.gemspec:17.
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /Library/Ruby/Gems/2.3.0/specifications/i18n-0.9.5.gemspec:17.
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /Library/Ruby/Gems/2.3.0/specifications/escape-0.0.4.gemspec:18.
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /Library/Ruby/Gems/2.3.0/specifications/coffee-script-source-1.11.1.gemspec:16.
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /Library/Ruby/Gems/2.3.0/specifications/em-websocket-0.5.1.gemspec:15.
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/gems/2.3.0/specifications/nokogiri-1.5.6.gemspec:22.
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /Library/Ruby/Gems/2.3.0/specifications/rouge-2.2.1.gemspec:18.
NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Gem::Specification#rubyforge_project= called from /Library/Ruby/Gems/2.3.0/specifications/sass-3.7.4.gemspec:21.
clang: error: no such file or directory: '10.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0'
clang: error: no such file or directory: '10.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/universal-darwin18'
clang: error: no such file or directory: '10.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include'
---------------------------------------------
Error loading the plugin `cocoapods-keys-2.2.0`.
CompilationError - error executing "xcrun clang -dynamic -bundle -Wl,-undefined,dynamic_lookup -Wl,-multiply_defined,suppress -g -Os -pipe -DHAVE_GCC_ATOMIC_BUILTINS -L. -I /Applications/Xcode 10.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0 -I /Applications/Xcode 10.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include/ruby-2.3.0/universal-darwin18 -I /Applications/Xcode 10.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/include -L/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib -o \"/Users/bhavin/.ruby_inline/ruby-2.3.0/Inline_OSXKeychain_5b2f8d1cd1bde9c4ff3fea49f09cd5c1.bundle\" \"/Users/bhavin/.ruby_inline/ruby-2.3.0/Inline_OSXKeychain_5b2f8d1cd1bde9c4ff3fea49f09cd5c1.c\" -lc -framework Security -framework CoreFoundation -framework CoreServices ": pid 8209 exit 1
Renamed /Users/bhavin/.ruby_inline/ruby-2.3.0/Inline_OSXKeychain_5b2f8d1cd1bde9c4ff3fea49f09cd5c1.c to /Users/bhavin/.ruby_inline/ruby-2.3.0/Inline_OSXKeychain_5b2f8d1cd1bde9c4ff3fea49f09cd5c1.c.bad
/Library/Ruby/Gems/2.3.0/gems/RubyInline-3.12.5/lib/inline.rb:621:in `build'
/Library/Ruby/Gems/2.3.0/gems/RubyInline-3.12.5/lib/inline.rb:859:in `inline'
/Library/Ruby/Gems/2.3.0/gems/osx_keychain-1.0.2/lib/osx_keychain.rb:17:in `<class:OSXKeychain>'
/Library/Ruby/Gems/2.3.0/gems/osx_keychain-1.0.2/lib/osx_keychain.rb:6:in `<top (required)>'
/Library/Ruby/Site/2.3.0/rubygems/core_ext/kernel_require.rb:72:in `require'
/Library/Ruby/Site/2.3.0/rubygems/core_ext/kernel_require.rb:72:in `require'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-keys-2.2.0/lib/keyring.rb:1:in `<top (required)>'
/Library/Ruby/Site/2.3.0/rubygems/core_ext/kernel_require.rb:72:in `require'
/Library/Ruby/Site/2.3.0/rubygems/core_ext/kernel_require.rb:72:in `require'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-keys-2.2.0/lib/cocoapods_plugin.rb:1:in `<top (required)>'
/Library/Ruby/Site/2.3.0/rubygems/core_ext/kernel_require.rb:92:in `require'
/Library/Ruby/Site/2.3.0/rubygems/core_ext/kernel_require.rb:92:in `require'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command/plugin_manager.rb:94:in `block in safe_activate_and_require'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command/plugin_manager.rb:94:in `each'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command/plugin_manager.rb:94:in `safe_activate_and_require'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command/plugin_manager.rb:31:in `block in load_plugins'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command/plugin_manager.rb:30:in `map'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command/plugin_manager.rb:30:in `load_plugins'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command.rb:326:in `block in run'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command.rb:325:in `each'
/Library/Ruby/Gems/2.3.0/gems/claide-1.0.3/lib/claide/command.rb:325:in `run'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.9.1/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.3.0/gems/cocoapods-1.9.1/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `<main>'
---------------------------------------------
[!] Your Podfile requires that the plugin `cocoapods-keys` be installed. Please install it and try installation again.
I have installed cocoapods-keys with 'sudo gem install cocoapods-keys', but I have no idea why my pod install is turning up all these errors. I'm tempted to remove my system Ruby and start over, but it seems from other answers like that's a bad idea.
Can someone help?
jeudi 9 avril 2020
RSpec - How to test the if-else block in update method of controller
Let's say I have a database to store the data of people (name, email). And there's an update method in the controller. The method is like:
def update
@people = People.find(params[:id])
if @people.update(people_params)
redirect_to people_path
else
render 'edit'
end
end
I wonder how can I test the situation that the update failed? Or do I really need to test it? I have searched it on StackOverflow, there is a link about it, but it not says if I should or should not to test it. Could anyone give me some help about it? If it can be test, how? Thank you so much!
rspec - How to test ActiveRecord::RecordNotFound?
I have a method to update people's attribute, and it will rescue ActiveRecord::RecordNotFound
if the people cannot be found. The method is:
def update
@people= People.find(params[:id])
if @people.update(people_params)
render json: { success: 'Success' }
else
render :edit
end
rescue ActiveRecord::RecordNotFound => e
render json: { error: 'Failed') }
end
And I want to test the situation when the record not found, here's my test for now:
let(:people) { create(:people) }
let(:people_id) { people.id }
let(:user) { people}
# Other tests...
context 'when person not found' do
let(:exception) { ActiveRecord::RecordNotFound }
# What should I write so that I can let the record not been found?
before { allow(Person).to receive(:find).and_raise(exception) }
it 'responds with json containing the error message' do
expect(JSON.parse(response.body)).to eq({error:'Error'})
end
end
I want my test executed under the condition that records not found. But I don't know how to do it. I tried to set let(people) {nil}
but it not work. Is there an anyway to do that? Thanks!
Rspec - Compare two json values
I got a response from render json: { success: 'Success' }
, I met a problem when I want to test if the response received the content like this. My unit test is:
let(:success) do
{
success: "Success"
}
end
it 'responds with json containing the success message' do
expect(JSON.parse(response.body)).to eq(success)
end
I got a failure from my test, which is:
expected: {:success=>"Success"}
got: {"success"=>"Success"}
I tried to add double quote to success:'Success'
so that it changed to 'success':'Success'
but still have the same problem. I have two questions, the first is why there's a colon before the success, and the second is how could I remove it?
Why many to many relationship in Rails connects also opposite way?
I have two models purchase_order and sale_order. These models are in a relation many to many with each other using has_and_belongs_to_many
The problem is that when I try to connect a purchase to a sale like:
SaleOrder.first.purchase_orders << PurchaseOrder.first
and then run in console
SaleOrder.first.purchase_orders
#it brings me the purchase order I connected. This is what I expected
PurchaseOrder.first.sale_orders
#it brings me the sale order I used to attach the purchase order. This is not what I expected.
In fact I don't want this to happen, because purchase_order.first will have is own sale_orders and I don't want the parent record. I expect to get an empty array in this case.
Rspec - How to test respond_to in my controller
I'm writing the rspec unit test for the update method of controller. The method is:
def update
@people = People.find(params[:id])
if @people.update(people_params)
respond_to do |format|
format.html {redirect_to people_path(@person), flash: { info:'Update Success'}}
format.js {render json: { success: 'Update Success' }}
end
else
render :edit
end
This method will update the people_params first and execute the repond_to, if the format is HTML, then the page will be redirected. If the format is JSON, it will render another JSON as response to my ajax request.
I just don't know how to write the rspec unit test for this, I have looked other questions and answers but still have no clue. Anyone could help me is appreciated!
mercredi 8 avril 2020
Module and Class with the same name in Ruby
I haven't found a solution, and am confused as to whether a solution is even possible or if I need to change names entirely.
Say, for example I have module 'A' and module 'B'. In module B, there is a class called 'A', just like module 'A'. Inside this class, I want to reference A::ClassC, where 'A' is the module, but I am getting errors because it thinks I am referencing the class A, which does not have ClassC. Can I get around this? Or do I need to rename one? (I would like to avoid that as much as possible)
NoMethodError in browser but work in Console
I'm a newbie for RoR 3, i have followed instruction from Simple Rails 2 book. I got NoMethodError in browser but when i tried from Console, it works without any error. Can any one help me ?
My full Code can view at Github : https://github.com/iamkevinhuang/shovel/
Can anyone help me ?
mardi 7 avril 2020
Looping through array targeting upcase letters only
Am trying to loop through a string which i have converted to an array and target only the upcase letters which i will then insert an empty space before the capitalized letter. My code checks for the first cap letter and adds the space but am struggling to do it for the next cap letter which in this case is "T". Any advise would be appreciated. Thanks
def break_camel(str)
# ([A-Z])/.match(str)
saved_string = str.freeze
cap_index =str.index(/[A-Z]/)
puts(cap_index)
x =str.split('').insert(cap_index, " ")
x.join
end
break_camel("camelCasingTest")
samedi 4 avril 2020
Include method in Ruby applied on an Array
I am having some trouble with the include? method in ruby. As I understand this method should return true if the array includes the specified element. Like this:
a = [ "a", "b", "c" ]
a.include?("b") #=> true
a.include?("z") #=> false`
But when I do this :
soap_opera = ["all", "my", "children"]
p soap_opera.include?("a")
It returns false. Why?
mercredi 1 avril 2020
how to write rspec test case for a controller method that output json?
I have a controller method which returns calls a modal to get json data. how/what tests to write , when output is json data?
class Homecontroller < ApplicationController
def show
req = foo.getjson();
req.post
end
end
Rails Running at 100% CPU
When I open vscode, and without running rails server, and I start modifying files the ruby process in my activity monitor spikes to 100% CPU usage. How should I go about debugging this I'm at a loss for direction.
how do i save response from haml form = select_tag
I'm not getting any way to get/save the response form the given select_tag.
@status = Status.values
= select_tag :status, content_tag(:option, 'status', :value=>"") + options_for_select( @status )