I am new in ruby on rails and i want to know the difference in details about PUT PATCH GET DELETE can any one help me ?
mardi 31 mai 2022
lundi 30 mai 2022
warning: constant ::Fixnum is deprecated: when running Rails system Test
/home/umairraza/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/bundler/gems/to_yn-19b0672ab1d4/lib/to_yn.rb:21: warning: constant ::Fixnum is deprecated /home/umairraza/Documents/remotecounsel/config/initializers/constants.rb:17: warning: already initialized constant STAGING_MAIL_RECIPIENTS /home/umairraza/Documents/remotecounsel/config/initializers/constants.rb:16: warning: previous definition of STAGING_MAIL_RECIPIENTS was here /home/umairraza/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-5.1.7/lib/action_dispatch/middleware/stack.rb:35: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call /home/umairraza/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-5.1.7/lib/action_dispatch/middleware/static.rb:109: warning: The called method initialize' is defined here /home/umairraza/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/scoping/default.rb:91: warning: Capturing the given block using Proc.new is deprecated; use
&blockinstead /home/umairraza/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/scoping/default.rb:91: warning: Capturing the given block using Proc.new is deprecated; use
&blockinstead /home/umairraza/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:167: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call /home/umairraza/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activerecord-5.1.7/lib/active_record/connection_adapters/column.rb:16: warning: The called method
initialize' is defined here Monkeypatch for ActionController::TestResponse is no longer needed rails aborted! LoadError: cannot load such file -- cuprite /home/umairraza/Documents/remotecounsel/test/application_system_test_case.rb:2:in <top (required)>' /home/umairraza/Documents/remotecounsel/test/system/rooms_test.rb:1:in
<top (required)>' bin/rails:4:in require' bin/rails:4:in
' Tasks: TOP => test:system (See full trace by running task with --trace) Coverage report generated for Unit Tests to /home/umairraza/Documents/remotecounsel/coverage. 373 / 17565 LOC (2.12%) covered. Stopped processing SimpleCov as a previous error not related to SimpleCov has been detected
samedi 28 mai 2022
Unable to Paste a PAT from GitHub to Cloud9 Ruby on Rails
I am trying to paste a Personal Access Token that I created in GitHub into the command line of a Ruby on Rails program I'm developing on Cloud9. I put in my GitHub username, and when I try to put in the PAT under password, it won't paste. I've tried with 2 different apps, but can't complete the git push. As a result I can't deploy my app to production.
I'm new at RnR, so have been learning using https://www.railstutorial.org/ following these instructions. I would appreciate any help I could get.
[website (main)]$ git remote add origin https://github.com/mhartl/hello_app.git
[website (main)]$ git branch -M main
[website (main)]$ git push -u origin main
After running the third command you will be prompted to enter your username and password. The username is simply your GitHub username, but the password is not your GitHub password; instead, the “password” must be a personal access token which you can create by following the instructions in the GitHub article “Creating a personal access token” I suggest selecting “No expiration” for the token expiration, and also be sure to select “repo” as the scope of the token so that it works at the command line. Once you’ve created and saved the personal access token, paste it in at the command line when prompted for a password to complete the git push
mercredi 25 mai 2022
Rails: no implicit conversion of Symbol into Integer
I have created a form where i have to get input from user,Here each article have unique id by which we fetch the article and from their we want to grab the value entered by user for that article I tried this but getting error. "no implicit conversion of Symbol into Integer"
this is my _form_data.html.erb code:
<%= form_for :fetch_content, url: article_path(@article), method: :get do |f| %>
<div class="form_data_id">
<%= f.text_field :paras, placeholder:"Enter value" %>
</div>
<span id="error"></span>
<div class="form_data_submit">
<input id="submitBtn" type="submit" name="commit" value="Save" data-disable-with="Save Api options" onmouseover="myFunction1()">
</div>
<% end %>
articles_controller.rb
<!-- Here i tried to get the value from User in count instance variable -->
def show
@article = Article.find(params[:id])
fetch_content
end
def fetch_content
p '@^$#%^^#%%%^%#$#$#%@#%$&&%&%##%$#$'
count = Article.find(params[:id][:api_options_paras])
if (count>5 && count <1)
@bacon = get_content(count,'all-meat')
else
@bacon = get_content(1,'all-meat')
end
end
This is my routes.rb file
# frozen_string_literal: true
Rails.application.routes.draw do
root 'articles#index'
get 'articles/:id/fetch_content',to: 'articles#fetch_content'
resources :articles do
resources :comments
end
end
getting error :
TypeError (no implicit conversion of Symbol into Integer):
app/controllers/articles_controller.rb:18:in `[]'
app/controllers/articles_controller.rb:18:in `fetch_content'
app/controllers/articles_controller.rb:13:in `show'
Started GET "/articles/1?api_options%5Bparas%5D=2&commit=Save" for ::1 at 2022-05-25 18:02:07 +0530
Processing by ArticlesController#show as HTML
Parameters: {"api_options"=>{"paras"=>"2"}, "commit"=>"Save", "id"=>"1"}
(0.1ms) SELECT sqlite_version(*)
↳ app/controllers/articles_controller.rb:12:in `show'
Article Load (1.3ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/articles_controller.rb:12:in `show'
"@^$#%^^#%%%^%\#$\#$#%@#%$&&%&%##%$\#$"
Completed 500 Internal Server Error in 54ms (ActiveRecord: 12.1ms | Allocations: 4648)
TypeError (no implicit conversion of Symbol into Integer):
app/controllers/articles_controller.rb:18:in `[]'
app/controllers/articles_controller.rb:18:in `fetch_content'
app/controllers/articles_controller.rb:13:in `show'
mardi 24 mai 2022
Rails – I want to change the status of my table by putting a certain time?
I've only been in RoR for a short time.
I have a list table with a field: status(enabled, disabled) and end_date, I have my form where I put a certain end time. I would like that when reaching this end time, the status field changes to disabled. is there anything i can do to achieve this ?
create_table "lists", force: :cascade do |t|
t.integer "user_id"
t.binary "uuid", limit: 36
t.string "name"
t.string "description"
t.datetime "end_date"
t.integer "status", default: 1
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_lists_on_user_id"
end
lundi 23 mai 2022
Ruby: selenium DriverExtensions returns unknow command
Every function from ::DriverExtensions give an erros:
POST /session/{session_id}/funciont did not match a known command
I'm specially interested in save_print_page(path):
@driver.save_print_page('path.pdf')
but the error is the one described below:
POST /session/731e8f40-b709-4090-845d-e6bdc794fcea/print did not match a known command
can you guys help me?
vendredi 20 mai 2022
Can i use VS code for UDEMY tutorial
I am having problems downloading the recommended IDE for UDEMY tutorial which cloud9 by amazon. i currently have VS code but i can not install ruby on rails which is a requirement for the set up environment to enable me begin the web developer training
mercredi 18 mai 2022
Ruby; How can I update the nested hashes in this one?
Sorry, it's a little bit too long. I need to change the status of :hero and :heroine to "dead"
def update_status
epic_tragedy = {
:montague => {
:patriarch => {name: "Lord Montague", age: "53"},
:matriarch => {name: "Lady Montague", age: "54"},
:hero => {name: "Romeo", age: "15", status: "alive"},
:hero_friends => [
{name: "Benvolio", age: "17", attitude: "worried"},
{name: "Mercutio", age: "18", attitude: "hot-headed"}
]
},
:capulet => {
:patriarch => {name: "Lord Capulet", age: "50"},
:matriarch => {name: "Lady Capulet", age: "51"},
:heroine => {name: "Juliet", age: "15", status: "alive"},
:heroine_friends => [
{name: "Steven", age: "30", attitude: "confused"},
{name: "Nurse", age: "44", attitude: "worried"}
]
}
}
I did add the code below inside the method but it shows error.
epic_tragedy[:montague][:hero][:status] = "dead"
epic_tragedy[:capulet][:hero][:status] = "dead"
Is there any additional step before I put those lines?
Initializer doesn't create instance in console
I am new to ruby and I am trying to create a hangman game, to do so I need to create a new game each time the user click on a button.
First step is to create the same object each time the methode create will be called (it will be different because of the .sample.
I am trying to create an object with the initialize method in my model.rbfile.
Here is my code :
class Game < ApplicationRecord
has_many :guesses
def initialize(*)
super
@word_to_guess = word_to_guess
@health_bar = 5
@game_status = game_status
end
def word_to_guess
words = [
"spokesperson", "firefighter", "headquarters", "confession", "difficulty", "attachment", "mechanical",
"accumulation", "hypothesis", "systematic", "attraction", "distribute", "dependence", "environment",
"jurisdiction", "demonstrator", "constitution", "constraint", "consumption", "presidency", "incredible",
"miscarriage", "foundation", "photography", "constituency", "experienced", "background", "obligation",
"diplomatic", "discrimination", "entertainment", "grandmother", "girlfriend", "conversation", "convulsion",
"constellation", "leadership", "insistence", "projection", "transparent", "researcher", "reasonable","continental",
"excavation", "opposition", "interactive", "pedestrian", "announcement", "charismatic", "strikebreaker",
"resolution", "professional", "commemorate", "disability", "collection", "cooperation", "embarrassment",
"contradiction", "unpleasant", "retirement", "conscience", "satisfaction", "acquaintance", "expression",
"difference", "unfortunate", "accountant", "information", "fastidious", "conglomerate", "shareholder",
"accessible", "advertising", "battlefield", "laboratory", "manufacturer", "acquisition", "operational",
"expenditure", "fashionable", "allocation", "complication", "censorship", "population", "withdrawal",
"sensitivity", "exaggerate", "transmission", "philosophy", "memorandum", "superintendent", "responsibility",
"extraterrestrial", "hypothesize", "ghostwriter", "representative", "rehabilitation", "disappointment",
"understanding", "supplementary", "preoccupation"
]
words.sample
end
def game_status
game_status = ["Game not started yet", "In Game", "You win", "You loose"]
game_status[0]
end
end
The problem is that when I do a Game.new in console, it returns :
[1] pry(main)> Game.new
=> #<Game:0x00007fa79b613290 id: nil, word_to_guess: nil, health_bar: nil, created_at: nil, updated_at: nil, guesse_id: nil, game_status: nil>
So the instance is not created and I don't know why.
Why is there an argument although I don't give an argument?
I am new to ruby and I am trying to create a hangman game, to do so I need to create a new game each time the user click on a button.
First step is to create the same object each time the methode create will be called (it will be different because of the .sample
.
I am trying to create an object with the initialize method in my model.rb
file.
Here is my code :
class Game < ApplicationRecord
has_many :guesses
attr_accessor :word_to_guess, :health_bar, :game_status
def initialize
@word_to_guess = words.sample
@health_bar = 5
@game_status = game_status[0]
end
words = [
"spokesperson", "firefighter", "headquarters", "confession", "difficulty", "attachment", "mechanical",
"accumulation", "hypothesis", "systematic", "attraction", "distribute", "dependence", "environment",
"jurisdiction", "demonstrator", "constitution", "constraint", "consumption", "presidency", "incredible",
"miscarriage", "foundation", "photography", "constituency", "experienced", "background", "obligation",
"diplomatic", "discrimination", "entertainment", "grandmother", "girlfriend", "conversation", "convulsion",
"constellation", "leadership", "insistence", "projection", "transparent", "researcher", "reasonable","continental",
"excavation", "opposition", "interactive", "pedestrian", "announcement", "charismatic", "strikebreaker",
"resolution", "professional", "commemorate", "disability", "collection", "cooperation", "embarrassment",
"contradiction", "unpleasant", "retirement", "conscience", "satisfaction", "acquaintance", "expression",
"difference", "unfortunate", "accountant", "information", "fastidious", "conglomerate", "shareholder",
"accessible", "advertising", "battlefield", "laboratory", "manufacturer", "acquisition", "operational",
"expenditure", "fashionable", "allocation", "complication", "censorship", "population", "withdrawal",
"sensitivity", "exaggerate", "transmission", "philosophy", "memorandum", "superintendent", "responsibility",
"extraterrestrial", "hypothesize", "ghostwriter", "representative", "rehabilitation", "disappointment",
"understanding", "supplementary", "preoccupation"
]
game_status = ["Game not started yet", "In Game", "You win", "You loose"]
end
When I do a Game.new
in my console, it returns this error message :
"ArgumentError: wrong number of arguments (given 1, expected 0) "
I dont understand, what argument am I giving ?
lundi 16 mai 2022
DynamoDB.create_table erroring with `ArgumentError: no such member :billing_mode`
I am trying to create a new table through the aws-sdk(2.11.31) using the DynamoDB client like so;
new_table_definition = {
attribute_definitions: [
{
attribute_name: 'user',
attribute_type: 'S'
},
{
attribute_name: 'timestamp',
attribute_type: 'N'
},
{
attribute_name: 'uuid',
attribute_type: 'S'
}
],
key_schema: [
{
attribute_name: 'uuid',
key_type: 'HASH'
},
{
attribute_name: 'timestamp',
key_type: 'RANGE'
}
],
global_secondary_indexes: [
{
index_name: 'user-timestamp-index',
key_schema: [
{
attribute_name: 'user',
key_type: 'HASH'
},
{
attribute_name: 'timestamp',
key_type: 'RANGE'
}
],
projection: {
projection_type: 'KEYS_ONLY'
},
provisioned_throughput: {
read_capacity_units: 0,
write_capacity_units: 0,
}
}
],
billing_mode: "PAY_PER_REQUEST",
provisioned_throughput: {
read_capacity_units: 0,
write_capacity_units: 0
},
table_name: "A_NEW_TABLE"
}
Dynamo::Table.create(new_table_definition)
However I get the following error: ArgumentError: no such member :billing_mode
From what I understand that is the correct key and formatting for the billing mode as described in the documentation for v2 of the sdk. Removing the billing mode creates the table fine but I am then forced to go into AWS console to manually change it to On-Demand.
Ruby - 2.3.3 Rails - 3.2.22.5 aws-sdk - 2.11.31
dimanche 15 mai 2022
To show your comment first if you are logged (and if you left a comment)
I am editing a Book-page improving the Comments-Area.
Now it is a "classic" area where the latest 3 comments are showed.
But I want to edit it showing first the comment left by the "logged user" (current_user
), if he is logged and if he already left a comment in this page, and then the 2 others (excluding the comment by current user already showed).
If it is not logged or there are no comments left by the current_user
, to show the latest 3 comments.
Now they are showed using a script in book_controller.rb
def load_comments!
@comments = @book.comments.roots.includes(:user).latest.limit(3)
end
As I said, I have to check if the user is logged and if he already left a comment.
So I was editing it in this way
def last_user_comment
current_user.comments
.order(created_at: :desc)
.where(book: @book)
.last if current_user
end
def load_comments!
@comments = @book.comments.roots.then do |base|
if last_user_comment
base.limit(2).to_a.unshift(last_user_comment)
else
base.limit(3)
end
end
end
is it good, right? It should work... but it doesn't work!! And my local host shows only "error 500", and I can not able to find the bug.
Tips?
mardi 10 mai 2022
Using Ros Apartment gem with ruby 3.0.0
After updating ruby version from 2.7.4 => 3.0.0 seems that ros-apartment gem cannot switch between tenants.
NoMethodError (undefined method `decode' for URI:Module):
lib/rescued_tenant_elevator.rb:10:in block in call' lib/rescued_tenant_elevator.rb:10:in
call'
After searching in documentation of ros-apartment seems that the problem is on generic call after calling @app.call(env)
My class for switching tenants
require 'apartment/elevators/subdomain'
class RescuedTenantElevator < ::Apartment::Elevators::Subdomain
def call(env)
super
rescue Apartment::TenantNotFound
[302, { 'Content-Type' => 'text/hml', 'Location' => Rails.application.routes.url_helpers.root_url }, self]
end
# needed to work
def each
end
end
Any idea ??
vendredi 6 mai 2022
Rspec test fails while rendering
For my user controller, while running the test cases I am facing render issue. It is redirecting to http://test.host/sign_in instead of rendering new.
- Controller code
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
UserMailer.registration_confirmation(@user).deliver_now
session[:user_id] = @user.id
format.html { redirect_to sign_in_path, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
- spec/users_controller_spec.rb
describe '#create' do
it 'User created' do
new_user = FactoryBot.build :user
post :create, params: {
user: {
id: new_user.id,
firstname: new_user.firstname,
email: new_user.email,
password: "s",
password_confirmation:"s"
}
}
expect(response).to render_template("new")
end
end
While running this test case I am facing this error!
- Error
Failures:
1) UsersController controller test cases #create User created
Failure/Error: expect(response).to render_template("new")
expecting <"new"> but was a redirect to <http://test.host/sign_in>
# ./spec/controllers/users_controller_spec.rb:30:in `block (4 levels) in <top (required)>'
How do I resolve this?
jeudi 5 mai 2022
Ruby Timeout.timeout does not timeout in x secs
Below code
Timeout.timeout(2) do
i = 0
while(true)
i = i + 1
p "test #{i}"
end
end
does not timeout in 2 secs. whereas below similar code timeout in 2 seconds
Timeout.timeout(2) do
i = 0
while(true)
i = i + 1
# p "test #{i}"
end
end
What is the underlying difference? Please help.
mercredi 4 mai 2022
Is there a way in Ruby to convert a inifile-like string into a json object?
Essentially, taking a string that would look something like this:
input_test = "
test1 = hello
test2 = goodbye
"
Is there a way with ruby to convert the string to be a json object?
input_test.convert_method()
puts input_test['test2'] #outputs 'goodbye'