jeudi 31 octobre 2019

Print Object attributes after creation in rails

I am new to rails and I want to jut print in the console the name of the lastly created record of Document. For this I am using in the model file, after? create callback.

Anyway I can not get the name displayed in the console after I run a procedure of creation. How can this be done to be able to display the name of the lastly created record of type Document?

 class Document < ApplicationRecord
  belongs_to :storage

  after_create :my_function

  def my_function
    puts Document.name
  end
 end

Setting default headers in Rails3 applications

I know that you can set default headers application wide in config/application.rb for Rails4+ apps but what is the accepted method in older versions of Rails, as in Rails3?

At the moment I am setting them in application_controller.rb as a before_filter method, but I think this is a bad practices and performance -impacting

https://edgeguides.rubyonrails.org/security.html?utm_source=twitterfeed&utm_medium=twitter#default-headers

How to access key, value in json / ruby

I have a json file like this, and I try to display the different value in my html:

{
    "testimonials": [
        {
            "office": "Test",
            "authors": "Benjamin",
        },
        {
            "office": "consultant",
            "authors": "Maxime ",
        },
        {
            "office": "DAF",
            "authors": "Alexandre",

        },
        {
            "office": "CEO",
            "authors": "Raphaël",
          },
        {
            "office": "Consultant",
            "authors": "Alexis",
        },
        {
            "office": "CEO,",
            "authors": "Sylvain",
        }
    ]
}

Could someone help me, for example, to access to display the value 'Alexis'

mercredi 30 octobre 2019

Multiple validates with :on in ruby

Hey I have a doubt if there is multiple validate in a line if :on at last whether all the validation are applicable to the :on or only the last validation.

//code validate :trial_account, :limit_for_account, on: :check_trial

// Whether only limit_for_account is validated on check_trial or both.

How to add count with active record association?

My Requirement is to send the count size of the database with active record association

I am trying to limit the size of record and want to load more options and clicking on load more will give all records

records = company.public_send(table).joins(:customer).where(customer_id: ids).order(sorting)
#records = records.count(:id) #300
records = records.limit(5)

This return me active record, along with this i want to send entire size of record How can i do it

mardi 29 octobre 2019

rake db:setup shows rake aborted! KeyError: key not found: "URL_HOST" error

i have rails app ubuntu 18.04. bundle install run successful but when i run rake db:setup it shows

rake aborted! KeyError: key not found: "URL_HOST" /var/www/myapp/code/config/environments/production.rb:71:in fetch' /var/www/myapp/code/config/environments/production.rb:71:inblock in ' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/railtie.rb:210:in instance_eval' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/railtie.rb:210:inconfigure' /var/www/myapp/code/config/environments/production.rb:3:in <top (required)>' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inrequire' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in block in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:240:inload_dependency' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:598:inblock (2 levels) in ' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:597:in each' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:597:inblock in ' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:30:in instance_exec' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:30:inrun' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:55:in block in run_initializers' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:44:ineach' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:44:in tsort_each_child' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:54:inrun_initializers' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:352:in initialize!' /var/www/myapp/code/config/environment.rb:5:in' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inblock in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:240:in load_dependency' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inrequire' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:328:in require_environment!' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:457:inblock in run_tasks_blocks' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/rake-13.0.0/exe/rake:27:in <top (required)>' /home/myappuser/.rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:ineval' /home/myappuser/.rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:in `' Tasks: TOP => db:setup => db:schema:load_if_ruby => environment (See full trace by running task with --trace)

Need help

How to do if condition check for value A against multiple values in Ruby on Rails?

I have a normal if condition. I have to check

if A IN (:B, :C ) {
 do something
}

But it is not working.

Call an action on button click in ruby on rails

I have an action defined in my lib directory. The action is used to send a get request in the server. I want to execute the function on button click. How can I do this? I know this is not the right approach. I am new to rails.

show_document.rb (in lib directory)

class Legaldoc::ShowDocument

def view_document(sessionID, token_document)
    require 'rest-client'
    require 'zip'
    res = RestClient::Request.execute(
        :method => :get,
        :url => "http://myurl.com",
        :headers => {
            :ldsessionId => sessionID,
        }
    )
  end
end

in my view file

<%= link_to 'Button', '#', :onclick => "view_document(sessionID, token_document)" %>

Rails3 create a global variable throughout application upon initialization

Currently we have a method in application_controller.rb which initialises a global variable or returns its value if it has been initialized.

Problem is this is being called upon each request, and its redundant because the variable is initialized after the first request.

How can I move this method to application.rb and have it run once upon Rails' initialisation

    config.after_initialize do
      begin
        @global_user = User.find(100)
      rescue => e
        Rails.logger.info "Error finding the Global User"
      end
    end

What is the correct way to fix bundler not finding compatible versions

I have an old rails 3 application which I want to update to rails 4 at the moment. I removed the Gemfile.lock manually and changed the Gemfile to require rails in version "4.0.0" before running a fresh "bundle install". I was getting several messages that bundler was not able to find compatible versions.

I am using ruby 2.0.0 here installed with rvm on a linux system.

I installed rails 4.0.0 manually using

gem install rails -v 4.0.0

And then I tried again with

bundle install

This is one example of the messages that pop up:

Bundler could not find compatible versions for gem "activerecord":
  In Gemfile:
    activerecord-import (~> 0.4.1) was resolved to 0.4.1, which depends on
      activerecord (>= 3.0)

    authlogic (~> 3.3.0) was resolved to 3.3.0, which depends on
      activerecord (>= 3.2)

    delayed_job_active_record (~> 4.0.0) was resolved to 4.0.3, which depends on
      activerecord (>= 3.0, < 5.0)

    rails (= 4.0.0) was resolved to 4.0.0, which depends on
      activerecord (= 4.0.0)

Due to the manual install of rails 4 I have activerecord in version 4.0.0 in my gems available. Why does it come up with that message? From my interpretation of the listed activerecord versions the dependency should be fulfilled with version 4.0.0? It is in the listed range between 3.0 and less than 5.

samedi 26 octobre 2019

Build A Ruby program code or Rubymine code with following:

Chapter 9 Assignment

CIS 116 Introduction to Programming

Build a Ruby code or Rubymine code with following:

You work for a software development company that wants to build and sell games that run in Windows. The company is in the process of creating a basic game engine. It wants everything to be object-oriented, so it needs to build the various classes that will be used in any of the games built in the future.

You have been assigned the task of building the Player class based on the specifications listed below. The class will be further developed in the future, but this initial class will help the team get started. Put all of your code in the same source file and name your file Ch9Asg.rb.

  • Create a Player class with a name and a health attribute. The health attribute must be an integer between 0 and 100. A Player with a health value of 100 is in excellent condition, and a Player whose health is 0 is essentially dead.

  • Create a class constructor that accepts two arguments that are assigned to the attributes.

  • Create a method that sets the health attribute given a value. If an attempt is made to set it below 0, set it 0; likewise, if an attempt is made to set the value higher than 100, set it to 100.

  • Create an attack() method that accepts a Player object named opponent as a parameter. Within the method, generate a random number between 0 and 25. If the value falls between 0 and 15, reduce the opponent’s health by that amount. If the value is over 15, consider the attack a failed attempt.

  • As the loop repeats, keep the user informed with what’s going on by showing the name and health of each player.

To test your class, create two Player objects, p1 and p2; give them different names. Build a loop that has p1 attacking p2; then, if p2 is still alive, it should attack p1. The loop should keep repeating until either p2 or p1 is dead, i.e. has a health value of 0. Display the winner at the end.

Submit your Ch9Asg.rb file on or before the due date. Be sure to comment your Player class well so that other programmers who use it know how it works and how to use it.

Is there a simple way I can query a Ruby on Rails join table in my view

New to RoR and struggling to make my table join work in my application views. I have 2 models Category and Pricing. They are joined through CategoryPricings .

Concept is a single Category can have multiple Pricings ( 4 pricing levels for the category ).

Where I am struggling is presenting the pricing information in my view when a category is selected.

So if I chose category (with id = 3) I would like the 4 price levels for that category to be presented.

My Models

 create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "pricings", force: :cascade do |t|
    t.string "overview"
    t.text "description"
    t.integer "delivery_time"
    t.integer "price"
    t.integer "pricing_type"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "category_pricings", force: :cascade do |t|
    t.bigint "category_id", null: false
    t.bigint "pricing_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["category_id"], name: "index_category_pricings_on_category_id"
    t.index ["pricing_id"], name: "index_category_pricings_on_pricing_id"
  end

My Controllers

class UsersController < ApplicationController

  before_action :authenticate_user!

  def dashboard
    #@user = User.find(params[:id])
    @categories = Category.find(params[:id])
  end

  def show
    @user = User.find(params[:id])
    @user_listings = @user.listings.paginate(:page => params[:page], :per_page => 5)
  end

  def index
    @user = User.paginate(:page => params[:page], :per_page => 5 )
  end

  def set_user
    @user = User.find(params[:id])
  end


  def update
    @user = current_user
    if @user.update_attributes(current_user_params)
      flash[:notice] = "Saved"
    else
      flash[:alert] = "Cannot update..."
    end
    redirect_to users_dashboard_path
  end

  private
  def current_user_params
    params.require(:user).permit(:from, :about, :status, :language, :avatar)
  end

  def category_params
    params.require(:category).permit(pricings: [])
  end

  protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:full_name, :username, :email, :password, :password_confirmation)}
  end

  # If you have extra params to permit, append them to the sanitizer.
  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
  end

  #The path used after sign up.
  def after_sign_up_path_for(resource)
    users_dashboard_path
  end

  def after_sign_in_path_for(resource)
    users_dashboard_path
  end

  def update_resource(resource, params)
    resource.update_without_password(params)
  end
end


  # def after_sign_in_path_for(resource)
  #   users_dashboard_path
  # end

  # The path used after sign up for inactive accounts.
  # def after_inactive_sign_up_path_for(resource)
  #   super(resource)
  # end

My Views Code

<footer class="card-footer">
    <% @categories.name %>

      <a class="has-text-danger is-block card-footer-item has-text-right">

      </a>
  </footer>

I am unfortunately not able get my view working so I can get the the list of prices for each category. Any help appreciated

jeudi 24 octobre 2019

iterate through elements in array within active record

I am trying to do a comparison and return a statement whether the item is inside of the array or not. Menu is an object that I have in active record which is composed of 3 attributes, the menu type, meal and the restaurant id. For the meal attribute I had a variable set to it which is actually an array that contains the names of meals.

In my code when I do puts"#{menu.meal}" I get back...

["Pancakes W/ Eggs and Bacon", "Bacon Egg and Cheese", "Oatmeal W/ Raisins", "Scrambled Eggs W/ Grits", "Blueberry Waffles W/ Syrup", "Chocolate Chip Pancakes W/ Sausage", "Yogurt Muffin"]

which is the array of meals that I have set in my seeds file. In the code below what I am trying to do is when the user enters the meal that it wants I want to search through all the meals if it exits, and if it does then the user can proceed and if not I want to output an error message saying that it does not exist.

 puts "What meal would you like to order"
 item_meal = gets.chomp


 menus_meals = res.menus.select do |menu|
   binding.pry
   menu.meal == item_meal

lundi 21 octobre 2019

Ruby: Check multiple keys in hash and delete it

I need to check if the given both keys is present in hash. Checking is not the problem here but one of the keys may not be present and can return false. I need to delete only the keys that are present.

if model_changes.has_key?(name)
   model_changes.delete(name)
end  

if model_changes.has_key?(id)
   model_changes.delete(id)
end

Instead of writing in two separate conditions is it possible to combine and delete the present key

Why ransank doesn't work with flutter chopper?

Can ransank work with flutter chopper?

My flutter project using chopper to call api server, which written using Rails.

   @Post(path: "orders_list")
      Future<Response> getOrderList(@Field('token') String authToken,  @Field('q[flow_gteq_any]') int flow,
            @Field('q[flow_lteq_any') int flow2);

I want server return data based on flow_gteq_any and flow_lteq_any, but it returns all data to me instead.

dimanche 20 octobre 2019

Rails Routing Clash When Rendering Static Pages

I have a routing clash. After moving all of my blog posts from /posts/:id to /:id (which is great), I now have an issue where my static pages don't contain an ID, so they aren't rendering. I don't want to have to process them through my posts controller.

Here's what I currently have in my routes.rb file:

  resources :posts, only: [:index, :create, :edit, :new, :destroy]
  get '/:id' => 'posts#show', :as => 'custom_url'
  match '/posts/:id' => redirect('/%{id}', status: 301)

But then these now don't work...

  match '/privacy' => 'static#privacy'
  match '/terms' => 'static#terms'

I have a controller called static_controller.rb which I can use if I need to. How can I jump over the /:id match.

samedi 19 octobre 2019

Date conversion in UTC

I am working ruby on rails. In that I have a doubt in date conversion from current timezone to UTC.

The date conversion function is

function date_conversion(date){
    out = moment(date, "DD/MM/YYYY").format('YYYY-MM-DD')
    var utc_time = moment.tz(out, zone).tz('UTC').format();
    return utc_time;
}

Here params date let as "12/10/2019" which is in string format and let the zone is ""Asia/Kolkata".

After executing the date_conversion function the values are

   out = moment(date, "DD/MM/YYYY").format('YYYY-MM-DD') 

The output of out = "2019-10-12"

   var utc_time = moment.tz(out, zone).format();

The value of utc_time is 2019-10-12T00:00:00+05:30. There is no problem while using above. But when i am trying to convert to UTC as below

    var utc_time = moment.tz(out, zone).tz("UTC").format();

I got 2019-10-11T18:30:00Z. In this situation I need of date in UTC but that date not to be changed. Please tell anybody some idea for this

vendredi 18 octobre 2019

cant rake db:migrate undefined method erorr

Hi guys I am new to rails and just getting started. Everytime I try to run rake db:migrate I get this(trace):

rake db:migrate == CreateModelNames: migrating =============================================== -- create_table(:model_names) rake aborted! StandardError: An error has occurred, all later migrations canceled:

undefined method feldtyp' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x7f729807cfa8>./db/migrate//20191018075455_create_model_names.rb:4:inup_without_benchmarks' ./db/migrate//20191018075455_create_model_names.rb:3:in up_without_benchmarks' (__DELEGATION__):2:insend' (DELEGATION):2:in `migrate' Tasks: TOP => db:migrate (See full trace by running task with --trace) david@david-desktop:~/Railsprojekte/david$ rake db:migrate --trace** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate == CreateModelNames: migrating =============================================== -- create_table(:model_names) rake aborted! StandardError: An error has occurred, all later migrations canceled:

undefined method feldtyp' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x7f61a32f62f8>./db/migrate//20191018075455_create_model_names.rb:4:inup_without_benchmarks' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/schema_statements.rb:104:in create_table' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:445:increate_table' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:346:in send' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:346:inmethod_missing' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:326:in say_with_time' /usr/local/lib/ruby/1.8/benchmark.rb:293:inmeasure' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:326:in say_with_time' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:342:inmethod_missing' ./db/migrate//20191018075455_create_model_names.rb:3:in up_without_benchmarks' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:280:insend' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:280:in migrate' /usr/local/lib/ruby/1.8/benchmark.rb:293:inmeasure' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:280:in migrate' (__DELEGATION__):2:insend' (DELEGATION):2:in migrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:480:inmigrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:556:in call' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:556:inddl_transaction' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:479:in migrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:466:ineach' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:466:in migrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:394:inup' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:377:in migrate' /usr/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/tasks/databases.rake:111 /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:240:incall' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:240:in execute' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:235:ineach' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:235:in execute' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:179:ininvoke_with_call_chain' /usr/local/lib/ruby/1.8/monitor.rb:242:in synchronize' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:172:ininvoke_with_call_chain' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:165:in invoke' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:150:ininvoke_task' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:106:in top_level' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:106:ineach' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:106:in top_level' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:115:inrun_with_threads' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:100:in top_level' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:78:inrun' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:176:in standard_exception_handling' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:75:inrun' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/bin/rake:33 /usr/local/bin/rake:26:in `load' /usr/local/bin/rake:26 Tasks: TOP => db:migrate

My code is this:

class CreateModelNames < ActiveRecord::Migration def self.up create_table :model_names do |t| t.feldtyp :feld_name

  t.timestamps
end

end

def self.down drop_table :model_names end end

Any help would be apreeated :)

LG

jeudi 17 octobre 2019

Rails Change common id of simple_form_for

I want to change form common name in rendering side

_from.html.haml
..
= f.simple_fields_for Image.new do |form|
      = render 'avatar_fields', f: form
..

_avatar_fields.html.haml
..
     = f.hidden_field :imageable_type
..

This is rendering like

<input id="product_image_imageable_type" name="product[image][imageable_type]" type="hidden">

But i want to render like this

<input id="product_logo_attributes_imageable_type" name="product[logo_attributes][imageable_type]" type="hidden">

I don't want to edit my '_avatar_fields.html.haml' screen. Because it's common html.

Any suggestion please..?

mercredi 16 octobre 2019

Ruby Rspec should_not_receive not working

For this below code snippet:

@by_hidden.should_not_receive(:by_limit).with(100).and_return(@by_limit)

I am facing error as

@by_hidden.should_not_receive(:by_limit).with(100).and_return(@by_limit)
       (Double Object).by_limit(100)
           expected: 1 time with arguments: (100)
           received: 0 times with arguments: (100)

Any information on this shall be appreciated.

Instance Variable in Ruby Resetting as Nil

My instance variables gets turned back to nil, even though it was set in a separate function that is called.

I've tried printing out before and after values for the instance variable, and have seen where it turns to nil. It's quite puzzling though. Attaching an example (https://repl.it/repls/FirebrickPresentKeyboard) also below:

class Test
  def process 
    return if a.nil? && b.nil?
    puts @some
  end

  def a
    @some = nil
    return true
  end

  def b
    @some = "abc"
    return false
  end

end

class Test2
  def process 
    return if c.nil?
    puts @hello
  end

  def c
    @hello = "hello"
    return true
  end
end

t = Test.new
t.process

t2 = Test2.new
t2.process

In the Test class, I expect @some to print "abc" since it is set during the "b" function. However, it prints nil.

In the Test2 class, I expect @hello to print "hello" and it certainly does.

mardi 15 octobre 2019

Halm ruby on rails : error Encountered a syntax error while rendering template:

I try to execute the following code but I have the error "Encountered a syntax error while rendering template:" and i can't fix it could someone help my ?

Here is my view :

%section
    %article
        - if @toss % 2 === 0
            %p the player #{@player_one.name} start the fight !
        - else 
            %p the player #{@player_two.name} start the fight !

        - while @hp_player_one > 0 && @hp_player_two > 0 
            - @hp_player_one -=  @player_two.attack
                %p  There is only #{@hp_player_one.to_s} point to #{@player_one.name}
            - @hp_player_two -=  @player_one.attack
                %p  There is only #{@hp_player_two.to_s} point to #{@player_two.name}
                -if @hp_player_one <= 0 && @hp_player_two > 0
                    %p #{@player_one.name} lost 
                -elsif @hp_player_two <= 0 && @hp_player_one > 0
                    %p #{@player_two.name} lost 
                -else 
                    %p draw ! 

lundi 14 octobre 2019

Faraday Json validation before .post

Currently using Faraday to do some http request to certain api. I want to validate the body and header at step of .post. However, when calling the .post the information is initialize and send asynchronously. (I did receive the Json schema validation from the API receiver side)

So! I was wondering if it is possible to setup a schema validation at the step of .post

I am able to use the Faraday_Middleware using the def call to intercept, but was it possible to turn the request into Json form and validate them?

how to "get" with Ruby on rails form

I try get 2 players from a list that i created, all I need is to get all the informations about those 2 players (name, descrption etc...) and once i have selected both, I need to be redirected to /fight path. My form doesnt work and I don't understand why. Could someone help me please ?

Here is my view :

<%= form_tag ("/fight", :method => "get") do %>
  <%= label_tag :player1 %>
  <%= select_field :character, @characters.collect{|u| [u.name, u.id]} %>
  <%= label_tag :playe2 %>
  <%= select_field :character, @characters.collect{|u| [u.name, u.id]} %>
  <%= form.submit 'Fight' %>
<% end %>

My pages_controller

def index 
  @characters = Character.all
end

And my routes

get 'fight' => 'pages#index'

dimanche 13 octobre 2019

Premailer-rails stopped working on rails version 3.2.22

I have included " gem 'premailer-rails'" in my Gemfile.

And include stylesheet like this : <%= stylesheet_link_tag "mailers/test" %> in mailer layout file, where path for css file is : app/views/layouts/test.html.erb.

For few days this configuration was working fine. But now it stopped , I an unable to figure out the reason.

My rails version is 3.2.22

Followed this link for my project : https://hackernotes.io/a-production-ready-rails-5-email-workflow-with-mailer-previews-premailer-and-activejob/

In Gemfile.lock : premailer (1.11.1) addressable css_parser (>= 1.6.0) htmlentities (>= 4.0.0) premailer-rails (1.10.3) actionmailer (>= 3) premailer (~> 1.7, >= 1.7.9)

Any leads will be very helpful.

samedi 12 octobre 2019

PG::Error: Wait on socket error (WaitForMultipleObjects)

I am using Rails 3 app on windows with ruby 1.9.3p551 and postgres(9.1.3) database. While running load test for the app, we're observing few request failure with error PG::Error: Wait on socket error (WaitForMultipleObjects) originating from activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:1153:in 'async_exec'.

Tried increasing connection pool of Postgres and checkout_timeout but same error keeps on coming during load test. Any idea/help on what could cause this issue will be very helpful. also, What could be the solution for this as at this time, we cant migrate to different version of ruby.

Thanks

jeudi 10 octobre 2019

Reading gz file in Ruby using Zlib. Zlib::GzipReader is reading only the first line of the file and not all lines

I have a gz file that I wanna parse. I am using Zlib::GzipReader library to open it. In console I have the file like this:

164] pry(main)> file
=> #<Zlib::GzipReader:0x00007fadbbfa5a08>
[166] pry(main)> Zlib::GzipReader.open(file.path){|gz| print gz.read }
"Date","Connection type code","Connection id","Currency","Impressions","Campaign","Traffic source","Clicks","Cost (EUR)","Country"
=> nil

Notice that, after reading the file and printing. I just got the first line but in fact, the file contains lots of lines and I wanna have them all

Rails 3 random database exceptions using postgres

One of our application is built on Rails 3 which uses postgres as database. We observe that while doing load test i.e continuously submitting request, there are random exceptions related to database (comes from postgres_adapter):

1. PG::Error: Wait on socket error (WaitForMultipleObjects):
2. NoMethodError: undefined method `result_error_field' for nil:NilClass: 

I am not able to find any reference on cause of these issues as they're coming at different points. Any help on how to avoid this or solve this would be helpful.

Thanks

mercredi 9 octobre 2019

on sign up if email already exist then render user on specific page with where i can display some messege

i just want to send confirmation instructions to user again if email already exist.

Thats what i've implemented, it just let user to sign Up if email is unique. if email already exist it just don't do anything.

class RegistrationsController < Devise::RegistrationsController
  layout 'pages'
  def new
    build_resource
    yield resource if block_given?
    respond_with resource
  end

  def create
    build_resource(sign_up_params)
    admin = User.create(first_name: "")
    resource.authenticatable = admin
    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: accounts_get_started_path(resource)
      end
    else
      byebug
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end

  def edit
    super
  end

  def update
    super
  end

  def destroy
    super
  end
end`enter code here`

mardi 8 octobre 2019

Duda sobre búsqueda en base de datos

Soy nuevo programando en Ruby on Rails y quisiera saber si me pueden ayudar con lo siguiente: Estoy intentando realizar la búsqueda de un estudiante con su cédula en la base de datos para saber cuáles y cuántos cursos ha realizado. La idea es que en la vista "Index" se digite el número de cédula y en la vista "Show" aparezca un listado con todos los cursos que ha realizado. Cabe resaltar que pueden aparecer uno, dos o más cursos.

He intentado realizar la búsqueda con la forma form_tag, con el método find y aún no lo he logrado.

Se espera que aparezca el listado de cursos realizados al buscar la cédula, pero no me está mostrando nada. Cabe resaltar que sí hay conexión a la base de datos y sí hay datos de ejemplo para mostrar.

How to remove [Thr-1] from Rails logs?

My logs are prepended with [Thr-1] or [Thr-2] and I can't figure out how to disable this behavior. I assume that they are the thread names, but I'm unsure.

lundi 7 octobre 2019

Rails Server exiting automatically immediately after start in newly cloned github repo

I have cloned a github repo and run the command bundle install, but after when I am starting the rails server it shows me the following error :

error message

What is the use of ! in rails

What is the use of ! in rails?

Especially in this line: From HArtl tutorial

users = User.order(:created_at).take(6)
50.times do 
    content = Faker::Lorem.sentence(5)
    user.each { |user| user.microposts.create!( content: content )}
end

Basically this is creating tweets/microposts for 6 users.

I am really wondering why need to use !

samedi 5 octobre 2019

How to resolve jekyll sass-converter error in Installation in Windows

I want to install jekyll, for that i have install ruby on rails (ruby version 2.3.3 and rails version) but the error i am facing in install is that jekyll sass-converter requires ruby version 2.4 from this link http://railsinstaller.org/en. I have downloaded and installed the other version 2.4 as well but got the error with version 2.5. How should I tackle this please guide me in this regard?

mardi 1 octobre 2019

asdf message "No version set for command rails" when running Rails server

I am trying to run my rails server (rails s) in my Rails 3.2.13 application after having updated my Ruby version in /.ruby-version and /.tools-versions, but get the following message:

`you might want to add one of the following in your .tool-versions file:

ruby 2.2.4`

However, I had updated ruby in both version files to 2.3.0 and it is reflected in both. When I type asdf which ruby the ruby version is also 2.3.0.

I'd like help understanding why rails s prompts this asdf message, and what I'm missing with how to fix it so that I can run the rails server.

HTTP parse error, malformed request (): #

i am running this on my localhost:3000 i am in the part in which i would signup and recieve a email activation and the email activation is in HTTPS, so im getting parse error. (Michael Hartl tutorial)

system:

I am running in windows 10.

ruby: bin: F:/Program/RailsInstaller/Ruby2.3.3/bin/ruby.exe version: ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

rails: bin: F:/Program/RailsInstaller/Ruby2.3.3/bin/rails.bat version: Rails 5.1.7

after creating the key and cert and bind it to my localhost i am getting an error below

rails s -b 'ssl://localhost:3000?key=/.ssl/localhost.key&cert=/.ssl/localhost.crt'

C:/Ruby23/lib/ruby/gems/2.3.0/gems/puma-3.11.0/lib/puma/binder.rb:149:in `check': SSL not available in this build (StandardError)

I have read that i need to install RubyInstaller-2.4 and newer to resolve this. but i am having issue on upgrading or pointing it to the new Rubyinstaller. Can someone guide me on what is the best setup in a windows OS or guide me on how to upgrade the rubyinstaller to 2.4, i have installed the latest 2.6 version but when i point it to this, it is giving me that the gems are missing.