mardi 23 février 2021

how to create query onChange form.select Rails

I create form.select with names from db. When user choose name I want to show table with all rows that this name have in db. How can I do that?

Thanks

ruby LDAPS connection reset by peer - SSL_connect

I am using WSL 2 with Ubuntu 20.04 and try to connect to the host which is implemented with LDAPS, When trying to connect with LDAP with port 389 everything works fine. But when tried to connect with LDAPS using the port 636, I am ending up getting "Connection reset by peerl - SSL_connect" error.

I am using the below configuration

    @host     = "hostname.example.com"
    @port     = "636"
    @user     = "admin"
    @password = "Password1!"

    tls_options = {
      verify_mode: OpenSSL::SSL::VERIFY_NONE
    }
    @msg = nil
    @connected = false
    @ldap = Net::LDAP.new host: @host, port: @port, base: @base,
    auth: { method: :simple, username: @user, password: @password },
    :encryption => {
      :method => :simple_tls,
      :tls_options => tls_options
    }
    @connected = true if @ldap.bind

I have even tried with start_tls as the encryption methond. Still not working. Later found out that the exact code works with the other computers. I would like to know what will be the bottleneck, why the connection is not working on my machine.?

Should there be any configuration that I need to update on the WSL2 on Ubuntu 20.04?

I am unable to find the difference.

any pointers would be highly helpful.

Thanks

lundi 22 février 2021

Hash method get on ruby

I need to get some values for a hash but, I don't know how can I do it! My data:

data = {
          name: "Pedro Álvares",
          age: 35,
          sensitive_data: {
            cpf_cnpj=>27046645678, 
            fantasy_name: "I have the power"
            }
        }

I search for ruby methods and find the method values_at, but this method gets only the first_data like name, age. If I use:

name = data.values_at(:name)

the field returned is Pedro Álvares but if I try use:

fantasy_name = data.values_at(:fantasy_name)

the data returned is nil.

How can I get the field without using data[:sensitive_data][:fantasy_name]?

Capistrano Deploy Fails missing production.log

I have taken over development of a rails project and am trying to run my first sandboxed deployment with capistrano. I am new to these technologies and am also in the process of researching via documentation and google, though I have not found what I am looking for just yet. I concede that I am no expert with these technologies and am probably not doing/missing something simple.

Since this is an old application the technologies are older versions. Capistrano 2.14.2 Ruby 1.9.3 RVM stable Rails 3.2.12

Using the command: bundle exec cap staging deploy BRANCH=master

My error: Rails Error: Unable to access log file. Please ensure that /var/www/app/releases/20210222154336/log/production.log exists and is chmod 0666. The log level has been raised to WARN and the output directed to STDERR until the problem is fixed.

I have verified that this file exists in the app/current/log directory and permissions are 0666 as well as the user is the app user. This is probably not enough info to help resolve my error, what else would be helpful? Any help in the right direction is appreciated.

vendredi 19 février 2021

Monkeypatching a ruby gem in ruby on rails

I am attempting to add changes to an existing method from a ruby gem that is defined as follows:

# lib/uppy/s3_multipart/client.rb
...

def this_method
  ...
end

I have installed the gem using bundler and then created a new file as follows:

# app/lib/s3_multipart.rb
require "uppy/s3_multipart"

class Uppy::S3Multipart::Client
  def this_method
    ...
    puts "Using monkeypatched method"
  end
end

My alternative method isn't being used, what am I doing wrong?

jeudi 18 février 2021

Iterate over database Record

I have database record which is like this

[#<Event:0x00007fbe7372de48
  @timezone="Europe/London">,
  @data={:foo=>"bar", :larry=>"lobster"},
  @id="first_event",
  @name="page_viewed",
  @occurred_at=Thu, 18 Feb 2021 21:16:57 UTC +00:00>,

#<Event:0x00007fbe7372de48
  @timezone="Europe/London">,
  @data={:foo=>"bar", :larry=>"test2"},
  @id="second_event",
  @name="page_viewed",
  @occurred_at=Thu, 18 Feb 2021 21:17:57 UTC +00:00>,

 #<Event:0x00007fbe7372f2e8
  @timezone="Europe/London">,
  @data={:foo=>"bar", :larry=>"lobster"},
  @id="second_event",
  @name="rfq_created",
  @occurred_at=Thu, 18 Feb 2021 21:19:57 UTC +00:00>

#<Event:0x00007fbe7372f2e8
  @timezone="Europe/London">,
  @data={:foo=>"bar", :larry=>"lobster"},
  @id="second_event",
  @name="rfq_created",
  @occurred_at=Thu, 18 Feb 2021 22:18:57 UTC +00:00>...]

Now i want fetch list of records when event name(@name) is page_viewed, started and selected i want to fetch only first event occurred record and if event name(@name) is rfq_created and purchased i want all the records of event name rfq_created and purchased

Here is what i have done :

 EVENTS = { "unique_kpi" => { "page_viewed" => 'UVisit',          
                              "start" => 'PVisit',
                              "selected" => 'SVisit' 
                             },
          "non_unique_kpi"=> {"rfq_created" => 'RfqCreated',
                              "purchased" => 'Purchased' 
                              }
}


def key_performance_indicators
  key_indicators = events.each_with_object({}) do |event, hash|
    if EVENTS["non_unique_kpi"].keys.include?(event.name)
      hash[event.name] = []  unless hash.has_key?(event.name)
      hash[event.name] << event
    else
      hash[event.name] = event unless hash.has_key?(event.name)
    end

  key_indicators.map do |key, value|
    kpi_class = indicator_class(key)
    "{kpi_class}".constantize.new(event: value)
  end
end


def indicator_class(kpi_key)
  EVENTS.find { |_k, hash| return hash[kpi_key] if hash.keys.include?(kpi_key) }
end

I want to refactor this in good way is there any other approach we can do this ? Please help.

lundi 15 février 2021

Creating Random Strinngs in Ruby with at least one sepcial character, one digit, one upper-case, one lowercase with no characters repeated in Ruby

My task is to generate a random string with following parameters:

  1. At least one Uppercase
  2. At least one lower
  3. At least one digit
  4. No repeated chars/digits allowed ( e.g. aa not allowed, aba is allowed, Aa is allowed)

I'm able to generate a random string with 1,2,3 parameters but parameter 4 logic is missing.

inputChars = [('a'..'z'), ('A'..'Z'),(0..9)].map(&:to_a).flatten
string = (0...16).map { inputChars[rand(inputChars.length)] }.join

vendredi 12 février 2021

Interrupted gem install on Mac

Long story short, I am new to rails. Started my first project and interrupted gem install. Now I keep getting this message whenever I go to create a new project. I am running a 2020 M1 MBP.

Rails is not currently installed on this system. To get the latest version, simply type: $ sudo gem install rails You can then rerun your "rails" command. sudo gem install rails Password: ERROR: While executing gem ... (Errno::EEXIST) File exists @ dir_s_mkdir - /usr/local/bin

WHAT DO I DO?

mardi 9 février 2021

Retrieve JSON from SQLite with Ruby on rails

I am trying to save the error_text and the error_code to the sqLite table in a json format. However When trying to retrieve the value, I am facing errors and could solve it. I am using the below code snippet to get the error_text from the table

<td id="generate_<%= u[:employee_id] %>">
      <% if nh.ad_status[:error_code] == 4444 %>
        Creating...
      <% else %>
        <%= link_to 'Generate', api_adam_account_generate_path(employee_id: u[:employee_id]), remote: true, id: "link_#{u[:employee_id]}" %>
          <% if nh&.ad_status.blank? %>
            <span id="msg_<%= u[:employee_id] %>"></span>
          <% else %>
            <span id="msg_<%= u[:employee_id] %>"> <%= nh&.ad_status[:error_text] %></span>
          <% end %>
      <% end %>
    </td>

And the below code I am using to update the json column in the table.

Newhire.where(employee_id: eid_).update(ad_status: { error_code: 4444, error_text: "AD Create"})

I can retrieve the entire json from table using the below code.

Newhire.where(employee_id: 2863020).pluck(:ad_status)

However, I only need to retrieve the error_code alone from the json Can anyone help me in solving this issue? Thanks in Advance

lundi 8 février 2021

expected ActiveRecord::RecordNotFound but nothing was raised

How to get the test pass for this error?

Rspec result

**2) Api::V1::UsersController GET #show - a user it fails showing a user
 Failure/Error:
   expect do
     get 'show', params: { id: 2 }
   end.to raise_error(ActiveRecord::RecordNotFound)
 
   expected ActiveRecord::RecordNotFound but nothing was raised
 # ./spec/controllers/users_controller_spec.rb:100:in `block (3 levels) in <main>'

** Controller -method

  def show
    begin
      user = User.find(params[:id])
      render json: UserSerializer.new(user).serialized_json
    rescue ActiveRecord::RecordNotFound => e
      render json: { error: e.to_s }, status: :not_found      
    end         
  end

**

Rspec controller

it 'it fails showing a user' do
  expect do
    get 'show', params: { id: 2 }
  end.to raise_error(ActiveRecord::RecordNotFound)
end

jeudi 4 février 2021

Active resource rails not fetching data

This is active.rb

class Active < ActiveResource::Base
    self.site = "http://localhost:3002/api/v1/users" # **When i run this it is not fetching data**

    self.site = Net::HTTP.get(URI.parse("http://localhost:3002/api/v1/users")) # **When i run this i can see the data in console. Will get error Bad URI**

end

welcome_controller.rb

 def index
    @active = Active.all
  end

I am Unable to fetch data from the using active resource. Please let me know Thank you

mercredi 3 février 2021

Error when try to display photos on homepage : "The asset "courses/image1" is not present in the asset pipeline"

I am newbie with Rails and trying to display photos to my homepage and here is my code at my home.html.erb

<br/>
<div class="row">
<% @courses.each do |course| %>
<div class="col m4">
<div class="card">
<div class="card-image">
 <%= link_to course do %>
    <%= image_tag "courses/#{course.image}" %>
  <% end %>
</div>
<div class="card-content">
  <span class="card-title"><%= course.title %></span>
  <% (1..course.star).each do %>
  <1 class="material-icons" green-text>grade</i>
  <% end %>
</div>
</div>
</div>
<% end %>
</div>

I made another page named "course" to upload photo to the homepage. Then, when I ran the code, it said to me that at the line <%= image_tag "courses/#{course.image}" %> there was an error. The asset "courses/image1" is not present in the asset pipeline.

Here is what I did.

First, I went to app/assets/images.

Second, I made folder which named "photos".

Third put image to the folder "photos". And Last I tried the code but there was the error.

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