mercredi 31 mars 2021

Accessing instance variables from outside the class

I'm having issues understanding this encapsulation. I have instance variables defined with attr_accessor. I'm trying to access them outside class. But they are always nil and returns undefined method.

NoMethodError: undefined method `has_key?' for nil:NilClass

Please help me understand.

class TrieNode
    attr_reader :value, :next, :children
    
    def initalize
        @value = nil
        @children = Hash.new
        @next = nil
    end
end

class Trie
    attr_accessor :root
    
    def initialize
        @root = TrieNode.new
    end
    
    def build_trie(strs)
        cur = @root
        
        strs.each do |str|
            str.chars.each do |char|
                if cur.children.has_key? char
                    cur = cur.children[char]
                    next
                else
                    new_node = TrieNode.new
                    cur.children[char] = new_node
                    cur = new_node
                end
            end
          cur = @root
        end
    end
end

React Rails : How to get the results of an API Call

I need the result of an api call to another server for a react component: let's say for now I just need to display either true or false as text

I have the following component:

// some_random_thing.coffee

    { div, h5 } = DOM
    actions = require '../../actions'
    
    class MfaQRCode extends React.Component
      @propTypes: {}
    
    
      constructor: ->
        super arguments...
        @validationTimeout = null
  shouldComponentUpdate: -> true

  render:->
    div {},
      @renderStatus()

  renderStatus: ->
    h5 {className: 'column-header'},
      "BOOLEAN::"
        @props.resource.boolean_record

Which is a child component of something else; Then to populate this boolean_record I have in my actions.coffee file

    api = require('./api')
    AddUserPopupActions = ReactUtils.actions.creators.popup
      somethingExists: { asyncResult: true }

AddUserPopupActions.somethingExists.listen ->
  @promise(api.somethingExists(arguments...))

In api.coffee

    api = ReactUtils.api
    
    class Api
    
    somethingExists: ->
      api.get "/servers/users/something/exists"

This get request is handled in a rails controller which I believe to be fine. My question is, how can I populate a variable so that I can use the result of the request which returns true or false from another server.

There is a method in a file named store.coffee where the resource component of props is populated I need to populate this with the result of the api request: have tried:

  onSomethingExists: (response) ->   
    @resource.boolean_record = response.responseJSON.result   
    @_update()          

But this method is not getting triggered at all it seems upon debugging. I'm very new to react and do not fully understand how it all works and given the fact coffeescript and rails are in the mix there is little information to be found on how to do this.

mardi 30 mars 2021

throw :warden not always caught by failure_app

I have a Ruby on Rails project (Rails 3.2, Ruby 1.9.3) in which there are two kinds of user and both of them are set up with devise. When the sing in fails for one kind of user (Pc), I wish to try if the credentials are correct for the other one (Tutor), since some Tutor users forget to use their specific login page. I created a custom failure app in which I recreate the call but for the other resource name. It works correctly if there is a user of type Tutor with the credentials (login succeeds). However, if the second attempt fails, the failure app is not called again and the warden error is not caught. I can't see why it would be called the first time but not the second. While debugging I have checked that warden.manager.config.failure_app keeps being my custom failure app through all the calls. Could anyone tell me if this is the expected behaviour? These are some key parts of the code:


class CustomFailureApp < Devise::FailureApp

  def respond
    if warden_options[:scope] == :pc && (warden_message == :invalid || warden_message == :not_found_in_database)
      params[:tutor] = params[:pc] # copy the credentials as if they were tutor credentials
      params.except!(:pc) # remove pc params
      flash.keep # it gets cleared otherwise, which leads to errors
      request.env["devise.mapping"] = Devise.mappings[:tutor]
      sessions_controller = SessionsController.new
      sessions_controller.request = request
      sessions_controller.response = response
      sessions_controller.process(:create)
    else
      super
    end
  end

#... other unrelated code
config.warden do |manager|
    manager.failure_app = CustomFailureApp
  end

What I observed is that in proxy.rb (warden gem), in:

   def authenticate!(*args)
      user, opts = _perform_authentication(*args)
      throw(:warden, opts) unless user
      user
    end

the first time, CustomFailureApp is called after throw(:warden, opts) unless user but on the second time it is not, it continues and leads to some other errors related to user being nil here

samedi 27 mars 2021

Rails console update

Hello I was trying the update the data in the table using the rails console.

Box.where("code = 'learning'").update(duration: 10)

I ran this command.

The data is temporarily changing.

Box.where("code = 'learning'")

When I run this the precious data is being displayed.

Could anyone let me the issue. Thank you in advance.

vendredi 26 mars 2021

How to remove tags from strings in html file?

For example if my field contains

description: "<p>Some Text </p>"

and I display it in my html.erb file as item.description How can I remove this p tags?

  <div class="preview__text">
          <%= sanitize(item.description) %>
        </div>

or

  <div class="preview__text">
          <%= item.description.html_safe %>
        </div>

jeudi 25 mars 2021

When do we use nested modules and nested classes in Ruby?

I came across two files which had a structure like this. What are some practical examples in which I will create File A to execute some code, and similarly when would the structure of File B be more useful ? I take it that the answer lies somewhere in reusability and name spacing ?, but I am not able to give myself a clear answer as to what the difference between these two are.

file_a.rb

module A
  module B
   // Code runs here
  end
end

file_b.rb

module A
  class B
   // Code runs here
  end
end

Rendering amount of months something was done in html.erb

I am wondering if it's possible to get amount of months in rails from response. If my data contains published.at: '2020-12-31 08:00:00 UTC'. How can I render in my html Published: 3 months ago instead of displaying the entire date? Now I display it as <%= item.published_at %>

mardi 23 mars 2021

How to extract value based on the header OR how to extract headers value from ods file in Ruby?

enter image description here

Want to extract values under "Location" header.

Ruby on Rails Tutorial Chapter 7 Integration Test Argument Error

Just starting with Rails and am working my way through Ruby on Rails Tutorial 6th edition. Things have been going great, been able to fix all issues, until now! I'm stuck on Chapter 7.3.4 while testing for Invalid Form Submissions. When running tests I receive the following:

ERROR["test_invalid_signup_information", #<Minitest::Reporters::Suite:0x00000001390c2d78 @name="UsersSignupTest">, 0.7315919999964535]
 test_invalid_signup_information#UsersSignupTest (0.73s)
Minitest::UnexpectedError:         ArgumentError: wrong number of arguments (given 2, expected 1)
            test/integration/users_signup_test.rb:8:in `block in <class:UsersSignupTest>'

  17/17: [===============================================================================] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.82379s
17 tests, 33 assertions, 0 failures, 1 errors, 0 skips

Here is the test file. I've tried testing both files and they produce the same error:

require "test_helper"

class UsersSignupTest < ActionDispatch::IntegrationTest

  test "invalid signup information" do
    get signup_path
    before_count = User.count
    post users_path, params: { user: { name: '',
                                       email: 'user@invalid',
                                       password:              'foo',
                                       password_confirmation: 'bar' } }
    after_count = User.count
    assert_equal before_count, after_count
    assert_template 'users/new'
  end
end
require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest

  test "invalid signup information" do
    get signup_path
    assert_no_difference 'User.count' do
      post users_path, params: { user: { name:  "",
                                         email: "user@invalid",
                                         password:              "foo",
                                         password_confirmation: "bar" } }
    end
    assert_template 'users/new'
  end
end

This is my first experience with Rails so any help would be super appreciated!

Formatting the datein html.erb

is it possible to format the date in my html file? Response I am receiving from item.starts_at

starts_at: '2018-01-10 07:28:00'. I would like to display this as Jan 10

lundi 22 mars 2021

How to sort loop based on response value from array

So below is a small structure how I loop items, I want to sort them in my loop from by amount of members to smallest, instead of it being randomly displayed? How should I approach this? Also, if loop contains only 2 elements, how can I set display div to none?

    <% for item in @items %>

<%= item.name %>
<%= item.members %>

<% end %>

samedi 20 mars 2021

Trying to set up route paths, getting no route match

I am having big issue setting up my views.. whenever I go on my page localhost/clear I get No route matches [GET] "/clear".

I have a folder named clear in my controllers with the controller files in it.

How do I set up this to be like:

localhost/clear as main view, 
and other one as
localhost/clear/connect
localhost/clear/test

clear.rb

class ClearController < ApplicationController  
    def index  
    end  
    end  

connect_controller.rb

class Clear::ConnectController< Clear::BaseController

    def index 
       @functions
end
end

routes.rb

  scope module: :clear, as: :clear do
    resources :connect, only: :index
    resources :test, only: :index

  end

mardi 16 mars 2021

The rails program does not create a database even though typed the code correctly?

I am newbie with rails and trying to create a new rails program with postgre database by this command rails new freelancer --database=postgresql

I typed it very carefully and I hoped that I could have a rails program with a database which configure in a database.yml file (something as they said on internet which I can connect to postsql).

But, my problem is, when I open my database.yml, here it is

default: &default
adapter: sqlite3
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
<<: *default
database: db/development.sqlite3
test:
<<: *default
database: db/test.sqlite3
production:
<<: *default
database: db/production.sqlite3

I do not know why it does not create the database for me as they said (they said that, if I use that command, the database could be created and will be created witl name freelancer_development which can be display in this file ?

Could you please give me some ideas ? Thank you very much for your comment.

Azure deploy Ruby not init

I can't upload app with git. When I access the app I got this message: No route registered for '/cancun.git'. Bash git push azure master

dimanche 14 mars 2021

TypeError no implicit conversion of Spree::Order into Hash

I am getting an error like this when I update the spree from 4.1 to 4.2 at the time of order creation.

Order Flow

  1. Add product into the cart
  2. Checkout product
  3. Address
  4. Shiping method
  5. Payment
  6. order completed and mail generated and this error displaying on success page TypeError no implicit conversion of Spree::Order into Hash

Cron-based terminal job doesn't start until screen unlocked (sometimes)

I have a cron job whose command line looks like:

30 5 * * * osascript -e 'tell application "Terminal" to do script "bash-script-file"'

FWIW the base script file sets some environment variables and then runs a Ruby program.

Prior to last week, most days this ran just fine, but occasionally (~ twice/month) it would hang until I either unlocked the screen or attached remotely to the system. At that time I would see a terminal screen with a message about new mail and a command line prompt with the bash-script-file on it. At that point, I could wait and the script would proceed to run normally. I have checked System Settings and the computer is set to sleep never. I'm not locking the screen (instead allowing it to go to sleep), and of course I have the screen saver locked, requiring a password to wake up.

Last week (about five days ago), I added a second cron job of the same form (running another bash script that started another Ruby program), and since then, both jobs have hung every day until I attached remotely. What is causing this? What can I do to resolve it?

tl;dr cron-scheduled terminal jobs are hanging until the screen unlocks.

vendredi 12 mars 2021

How to redirect to Not Found page if an invalid URL is passed on Active Admin?

I'm using ActiveAdmin gem in my Rails application. I have an Item resource in the ActiveAdmin. I have allowed all the actions except new.

actions :all, except: [:new]

But in the URL if explicitly passed /admin/items/new, it throwing an ActiveRecord::Not Found error as it taking new as an id. In the description of the error, it is showing "Couldn't find Item with 'id'=new. I want to redirect to 404 or Not found page if an invalid url is passed. Can someone help me with this? Thanks is advance!

jeudi 11 mars 2021

Información de curso de ruby [closed]

alguien me recomiende donde realizar un un curso de ruby que sea bueno, y que ya hayan hecho. gracias.

Find Specific value of hash using ruby

I am trying to extract the value of the skuPartNumber from the below hash

{:error_code=>0, :data=>{"@odata.context"=>"https://graph.microsoft.com/v1.0/$metadata#users('xyz.yxz@domain.com')/licenseDetails", "value"=>[{"id"=>"88sGumHGlkiNvM0ZAFLCmUmPksW6EvdIraMNdDo2AdU", "skuId"=>"c5928f49-12ba-48f7-ada3-0d743a3601d5", "skuPartNumber"=>"SKUPartName1", "servicePlans"=>[{"servicePlanId"=>"da792a53-cbc0-4184-a10d-e544dd34b3c1", "servicePlanName"=>"ONEDRIVE_BASIC", "provisioningStatus"=>"Success", "appliesTo"=>"Company"}, {"servicePlanId"=>"2bdbaf8f-738f-4ac7-9234-3c3ee2ce7d0f", "servicePlanName"=>"VISIOONLINE", "provisioningStatus"=>"Success", "appliesTo"=>"Company"}, {"servicePlanId"=>"113feb6c-3fe4-4440-bddc-54d774bf0318", "servicePlanName"=>"EXCHANGE_S_FOUNDATION", "provisioningStatus"=>"PendingProvisioning", "appliesTo"=>"Company"}, {"servicePlanId"=>"663a804f-1c30-4ff0-9915-9db84f0d1cea", "servicePlanName"=>"VISIO_CLIENT_SUBSCRIPTION", "provisioningStatus"=>"Success", "appliesTo"=>"Company"}]}, {"id"=>"88sGumHGlkiNvM0ZAFLCmZK4DfPpB-lHg3yAcn9G_T0", "skuId"=>"f30db892-07e9-47e9-837c-80727f46fd3d", "skuPartNumber"=>"SKUPartName2", "servicePlans"=>[{"servicePlanId"=>"113feb6c-3fe4-4440-bddc-54d774bf0318", "servicePlanName"=>"EXCHANGE_S_FOUNDATION", "provisioningStatus"=>"PendingProvisioning", "appliesTo"=>"Company"}, {"servicePlanId"=>"17ab22cd-a0b3-4536-910a-cb6eb12696c0", "servicePlanName"=>"DYN365_CDS_VIRAL", "provisioningStatus"=>"Success", "appliesTo"=>"Company"}, {"servicePlanId"=>"50e68c76-46c6-4674-81f9-75456511b170", "servicePlanName"=>"FLOW_P2_VIRAL", "provisioningStatus"=>"Success", "appliesTo"=>"Company"}]}]}}

However, I tried using result[:data]['value']['skuPartNumber'] and result in the error.

How can extract the skuPartNumber where the SkuPartNumber is equal to "skuPartName2" from the above hash.

I can extract values with

result[:data]['value'][0]['skuPartNumber']

But would like to get the result based on specific value by providing skuPartNumber

Any help would be helpful.

Thanks

mercredi 10 mars 2021

Setting up database for the first time in ruby on rails

I am very much fresh in using Ruby on rails. I have cloned a git repo and trying to set up a PostgreSQL database in my local machine(Win 10).

Ruby version- 2.4.10
Rails - 5.2.0

I am using the below command

rake db:setup RAILS_ENV=development

Error Output -

rake aborted!
NoMethodError: undefined method `[]' for nil:NilClass
D:/ruby/reserves/config/environments/development.rb:41:in `block in <top (required)>'
D:/ruby/reserves/config/environments/development.rb:1:in `<top (required)>'
D:/ruby/reserves/config/environment.rb:5:in `<top (required)>'
Tasks: TOP => db:setup => db:schema:load_if_ruby => db:create => db:load_config => environment
(See full trace by running task with --trace) 

In database.yml file there are three environments has been declared - Development/Production/test

development:
  <<: *default
  database: reserves-dev
  username:****
  password:****
  host: localhost

How can I set the environment variable to development for setting the database in my local.

Any help is highly appreciated.

Thank you in advance.

lundi 8 mars 2021

What is the best gem for managing con jobs?

I want to write a cron job in order to shoot a notification about an event happening soon. I want to notify the participants about the event one day before it's happening day. I want to call a controller method which will check event start date and if it is happening tomorrow it should be called automatically and send notifications to the participants.I tried whenever gem but did not work for me or might be I don't know how to use it for my case. Please suggest me a good gem which will fit in my use case. Thanks.

samedi 6 mars 2021

After changing my Rails Version to 6.0.3.5 from 6.1.3 for Heroku. I have got a Runtime Error after running Rails S

enter image description here

When deploying basic app for the first time to Heroku I had to change my Rails Version to 6.0.3.5 from 6.1.3 because Heroku wasn't working on Rails 6.1.3. After changing the version to 6.0.3.5 in the Gemfile and running "bundle" and "bundle update". I am getting a Runtime error as attached. I am a beginner, help to right direction would be great.

vendredi 5 mars 2021

RSpec: Can we configure an expectation to return two different value? I want to test retry mechanism

So I have a retry rule in my application. I wanted to test that using rspec.

When I call service without passing account ID it should give me false and when account ID is passed it should give me true.

I am trying this code

options = {
  email: 'dev@dev.com'
}
expect_any_instance_of(PaymentService::CreatePayment).to receive(:call)
                                                           .with(options)
                                                           .and_return(false)
options[:account_id] = 12345
expect_any_instance_of(PaymentService::CreatePayment).to receive(:call)
                                                           .with(options)
                                                           .and_return(true)

But this doesnt work for me.

Rails upsert using find_or_create_by, create_with and optional chaining

I am using below code to upsertmy Model which works correctly but is verbose. I wanted to shorten it by using find_or_create_by, create_with and optional chaining but it is not working as expected.

Can someone please advice...

Verbose Code which works -

user_attr = {
              first_name: 'Scarlett',
              last_name: 'Johansson',
              profession: 'Actress',
              address: 'Los Angeles'
            }

....
existing_user = User.find_by(first_name: user_attr.fetch(:first_name), 
                             last_name: user_attr.fetch(:last_name))
if existing_user
  existing_user.update!(user_attr)
 else
  User.create!(user_attr)
end

Output:
# => #<User id: 2, first_name: "Scarlett", last_name: "Johansson", profession: "Actress", address: "Los Angeles">

Shorter version which does not return correct output:

User
  .create_with(user_attr)
  .find_or_create_by(first_name: user_attr.fetch(:first_name), 
                     last_name: user_attr.fetch(:last_name))

Reference - https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by

mardi 2 mars 2021

How to deep copy in ruby without using marshal?

this is what my project says :- "You must implement deep copying of lists yourself, without relying on Ruby constructs for marshalling and unmarshalling data structures" How do you do that?

How to make sure that mongoid attribute values are updated in a specific order?

I have an enum enumerize :message_status, in: [:sent, :delivered, :read, :error] in my mongoid class WhatsappLog. I want to make sure that the message status can be updated only in this particular order. "sent" -> "delivered" -> "read". For example, if the message status for a particular document is "delivered", I want to prevent it from being changed to "sent".