vendredi 28 avril 2023

How to validate an updated has-many-through collection

I am try to figure out how to properly validate a model collection whenever that collection is updated using the << collection operator. In our legacy app (Rails 3.2.1), I found that platform_collection_obj.platforms is updated using << operator

Example:

collection.platforms << new_platform

In researching how to validate that each platform in platforms collection has appropriate data, I found that I should use custom-validation function. So I tried adding each_platform_branch_id validation function to PlatformCollections Model. However, I found in testing (via rails console) that the validation was not triggered.

In reading Has-Many-Association-Collection Info, I came across this

Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. Note that this operation instantly fires update SQL without waiting for the save or update call on the parent object, unless the parent object is a new record. This will also run validations and callbacks of associated object(s).

This excerpt indicates that using << to perform update on collection.platforms will not trigger the parent validations, which in this case would be the PlatformCollection:each_platform_branch_id validation function. I know that manually perforning collection.save would trigger validation, but it would be too late b/c << has already updated the DB.

So to restate the question is: How do I properly validate a has-many-through-model collection whenever that collection is updated using the << collection operator?

PlatformCollections Model

class PlatformCollection < ActiveRecord::Base
  belongs_to :tezt
  has_many :platform_collection_platforms, :order => "platform_collection_platforms.default DESC"
  has_many :platforms, :through => :platform_collection_platforms, :order => "platform_collection_platforms.default DESC"

  def each_platform_branch_id
    platforms.each do |p|
      if p.branch_id != @branch.id
        err_msg = "Invalid Platform: #{p.to_json} for PlatformCollection: #{self.to_json}. " \
                  "Expected Branch: #{@branch.id}, Actual Branch: #{p.branch_id}"
        errors.add(:platform, err_msg)
      end
    end
  end

Platforms Model

class Platform < ActiveRecord::Base
  attr_accessible :name
  belongs_to :branch
  has_many :platform_collection_platforms
  has_many :platform_collections, :through => :platform_collection_platforms

Can't set changePasswordAtNextLogin to true - Google Admin Directory V1 API Rails

I am using the google-apis-admin_directory_v1 gem for Rails. According to the documentation, if you set the field changePasswordAtNextLogin to true in the insert user method it Indicates if the user is forced to change their password at next login however, when I have created users via the API with this attribute set to true it has not asked me to change my password. Here is my method call:

google_name =
      Google::Apis::AdminDirectoryV1::UserName.new(
        given_name: 'John',
        family_name: 'Smith',
        full_name: 'John Smith'
      )
    google_user =
      Google::Apis::AdminDirectoryV1::User.new(
        password: 'password',
        primary_email: 'john.smith@example.com',
        name: google_name,
        change_password_at_next_login: true
      )

jeudi 27 avril 2023

Respond_to format in Rails 5

I am having problems getting respond_to format working in Rails 5 app in controller, is just for downloading a csv list of users, as below: def customers_graylist_export @graylisted_users = Customer.where(status_trust: 'graylist') respond_to do |format| format.csv do response.headers['Content-Type'] = 'text/csv' response.headers['Content-Disposition'] = "attachment; filename=ListaCinza.csv" end end end

And getting unknown format error on line "respond_to do |format|" the mime type is registered in mime_types initializer, and this should be straightforward, but Rails 5 is a little quirky!

Any suggestions welcome?

Many Thanks

mardi 25 avril 2023

HTTPS request for ruby

I would like to take information from another website. Therefore (maybe) I should make a request to that website (in my case a HTTP GET request) and receive the response.

How can I make this in Ruby on Rails?

If it is possible, is it a correct approach to use in my controllers?

if another website is http://www.test.com, it OK but https://www.test.com,

i got it SyntaxError ((eval):1: syntax error, unexpected '<'

^ (eval):2: syntax error, unexpected tCONSTANT, expecting end-of-input 404 Not Found ^~~): app/models/cart_payment.rb:155:in `eval'

SyntaxError ((eval):1: syntax error, unexpected '<'

^ (eval):2: syntax error, unexpected tCONSTANT, expecting end-of-input 404 Not Found ^~~): app/models/cart_payment.rb:155:in `eval'

url = URI.parse("https://test.com")

  http = Net::HTTP.new(url.host, url.port);
  request = Net::HTTP::Post.new(url)
  request["Content-Type"] = "application/json"

  request.body = JSON.dump(body)

  response = http.request(request)

  response_body = eval(response.read_body)

  message = response_body[:Response]

Not able to install ruby 2.3.1 in ubuntu 22.01 using rbenv

Not able to install ruby 2.3.1 in ubuntu 22.01 using rbenv it is giving the fllowing error response:

vidur@Vidur-PC:~/rails_apps/Connectivity-Web$ rbenv install 2.3.0
To follow progress, use 'tail -f /tmp/ruby-build.20230425154726.452387.log' or pass --verbose
Downloading openssl-1.0.2u.tar.gz...
-> https://dqw8nmjcqpjn7.cloudfront.net/ecd0c6ffb493dd06707d38b14bb4d8c2288bb7033735606569d8f90f89669d16
Installing openssl-1.0.2u...
Installed openssl-1.0.2u to /home/vidur/.rbenv/versions/2.3.0

Downloading ruby-2.3.0.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.bz2
Installing ruby-2.3.0...

WARNING: ruby-2.3.0 is past its end of life and is now unsupported.
It no longer receives bug fixes or critical security updates.


BUILD FAILED (Ubuntu 22.10 using ruby-build 20230424)

Inspect or clean up the working tree at /tmp/ruby-build.20230425154726.452387.KXKRoa
Results logged to /tmp/ruby-build.20230425154726.452387.log

Last 10 log lines:
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/store.rb:749:in `save'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/generator/ri.rb:27:in `generate'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:535:in `block in generate'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:530:in `chdir'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:530:in `generate'
    /tmp/ruby-build.20230425154726.452387.KXKRoa/ruby-2.3.0/lib/rdoc/rdoc.rb:513:in `document'
    ./bin/rdoc:20:in `<main>'


make: *** [uncommon.mk:442: rdoc] Error 1

please suggest the possible solution thanks in advance.

samedi 22 avril 2023

How to get out of a wrong folder

I'm supposed to be in LizzyOrji123/blog in my GitHub.

Now I'm in /home/lizzy123/Elizabeth -profile-picture/blog

What command should I put in to get into the right folder?

The wrong folder is not allowing me to access .json

I want to be able to access my package.json file. Currently, it says I couldn't find it using yarn

vendredi 21 avril 2023

Ruby `.in?` mean?

I am very new to ruby, I saw a line if !'Region' .in? region. What does .in? mean? I tried searching for this in all the blogs but could not find any. Please share the relavant documentations if any.

jeudi 20 avril 2023

How to add sorting to a column with dynamic data in active admin

I have a column Average that gets the value :total from db and we are doing total/3 in average column. as follows

index do
    selectable_column
    id_column
     column 'Average', sortable: true do |object|
      object.total/3
    end
end

I want to add sorting to this column. Can someone please help me with this one?..

mardi 18 avril 2023

My search bar for my Ruby on Rails website seems to be routed wrong

I am currently trying to re-create John Elders creating a weather app project and with the newer version of Bootstrap, my navbar doesn't look like his. Throughout the project, I worked through the differences in the 2 different search bars, but when he went to type in the area code for the project, his localhost:3000 took him to a 3000/zipcode which I don't know why mine won't do the same. It feels like the search bar is just not responding to my typing.

Navbar

<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">My Ozone</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-   target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
    
    

      </ul>
  
      <``form class="d-flex" role="search">
      <%= form_tag zipcode_path, :method => 'POST' do %>
        <% text_field_tag 'zipcode', nil, placeholder: "Search Zipcode", class: "form-control me-2" %>
        <% submit_tag 'Search', class: 'btn btn-outline-success my-2 my-sm-0' %>
        <input class="form-control me-2" type="search" placeholder="Search Zipcode" aria-label="Search Zipcode">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    
        <% end %>
      </form>
    </div>
  </div>
</nav>

Application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Weather</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>

  <body>
    <%= render 'home/navbar' %>
    <div class="containter">
      <br/>
      <%= yield %>
    </div>
  </body>
</html>

index.html.erb

</style>


<div class="jumbotron <%= @api_color %>">
  <h1 class="display-4"><%= @final_output %></h1>
  <p class="lead">This is the current ozone air quality reaout for my neighborhood in Poquoson, VA</p>
  <hr class="my-4">
  <p><%= @api_description %></p>
  <br/>
  <p class="lead">

</div>

home_controller.rb

class HomeController < ApplicationController
  def index
    require 'net/http'
    require 'json'

    @url = 'https://www.airnowapi.org/aq/observation/zipCode/current/?   format=application/json&zipCode=23662&distance=25&API_KEY=B4B8AEE7-95A3-413F-B122-9F3DDCE35C85'
    @uri = URI(@url)
    @response = Net::HTTP.get(@uri)
    @output = JSON.parse(@response)

    # Check for empty return results
    if @output.empty?
        @final_output = "Error"
    elsif !@output
        @final_output = "Error"
    else
        @final_output = @output[0]['AQI']
    end

    if @final_output == "Error"
        @api_color = "gray"
    elsif @final_output <= 50
        @api_color = "green"
        @api_description = "Good (0-50) Air quality is considered satisfactory, and air pollutioon poses little or no risk."
    elsif @final_output >= 51 && @final_output <= 100
        @api_color = "yellow"
        @api_description = "Moderate (51-100) Air quality is acceptable; however, for some pollutants there may be a moderate health concern for a very small number of people who are unusually sensitive to air pollution."
    elsif @final_output >= 101 && @final_output <= 150
        @api_color = "orange"
        @api_description = "Unhealthy for Sensitive Groups (101-150) Although general public is not likely to be affected at this AQI range, people with lung disease, older adults and children are at a greater risk from exposure to ozone, whereas persons with heart and lunch disease, older adults and children are at greater risk from the presence of particles in the air."
    elsif @final_output >= 151 && @final_output <= 200
        @api_color = "red"
        @api_description = "Unhealthy (151-200) Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects."
    elsif @final_output >= 201 && @final_output <= 300
        @api_color = "purple"
        @api_description = "Very Unhealthy (201-300) Health alert: everyone may experience more serious health effects."
    elsif @final_output >= 301 && @final_output <= 500
        @api_color = "maroon"
        @api_description = "Hazardous (301-500) Health warnings of warnings of emergency conditions. The entire population is more likely to be affected."

    end
  end

  def zipcode
    @zipquery = params[:zipcode]
    if params[:zipcode] == ""
      @zip_query = "Hey you forgot to enter a zipcode!"
    elsif params[:zipcode]

    end
  end
end

routes.rb

Rails.application.routes.draw do
  get 'home/zipcode'
  root 'home#index'

  post "zipcode" => 'home#zipcode'
end

zipcode.html.erb

Zipcode page!
<br/>

<%= @zip_query %>

Sorry for bombarding with all this code, I am just confused on where I went wrong and why it will not let me search.

I tried changing my <form tag to <div and it seemed to do something, but not what I needed. Also I tried re-routing everything, but considering I'm quite new, I think I messed something up along the way.

vendredi 14 avril 2023

Can I generate a one time use token with doorkeeper specific to one API endpoint?

I am using Ruby on Rails and doorkeeper to control client auth. I am looking for a way to generate an access token that is only useful for a specific API endpoint. The goal is to send a link via email to that endpoint. I want to include the access token so they don't need to log in. However, I don't want anyone with the link to be able to log in and do whatever they want, they should only be allowed to use said endpoint with that token. Is that possible?

Ruby: creating a Zip file

I have following code that I use for create .gz.tar file but now I need to change it to .zip formant


create_tarball = lambda do |tarball, files, config, id|
  File.open(tarball, 'wb') do |t|
    Zlib::GzipWriter.wrap(t) do |gz|
      Gem::Package::TarWriter.new(gz) do |tar|
        content = "#{config.join("\n")}\n"
        tar.add_file_simple("file.example", 0o644, content.length) do |io|
          io.write(content)
        end
        files.each do |file|
          mode = File.stat(file).mode
          File.open(file, 'rb') do |f|
            tar.add_file_simple(File.basename(file), mode, f.size) do |io|
              io.write(f.read)
            end
          end
        end
      end
    end
  end
end

how can i convert this logic to do same thing but into a Zipfile, please help

i tried to do this but it doesn't work

create_tarball = lambda do |tarball, files, config, id|
  File.open(tarball, 'wb') do |t|
    Zip::File.open(zipfile_name, create: true) do |zipfile|
      Zip::OutputStream.write_buffer do |zip|
        content = "#{config.join("\n")}\n"
        zip.put_next_entry("file.example")
        zip.write(content)
        end
        files.each do |file|
          mode = File.stat(file).mode
          File.open(file, 'rb') do |f|
            tar.add_file_simple(File.basename(file), mode, f.size) do |io|
              io.write(f.read)
            end
          end
        end
      end
    end
  end
end

jeudi 13 avril 2023

Update a monthly payment subscription to a single payment after a failed payment? Or allowing the customer to do so or not

Let say my customer has to pay 10$ every month for 12 month. But the first payment, or second or any other payment among the 12, will fail for x reason.

I'd like to offer the possibility to pay the full subscription (or what's left to pay) as a single payment.

Unfortunately when i update my line_item with a single payment price object, Stripe raise this error:

Stripe::InvalidRequestError - You cannot update a subscription in incomplete status in a way that results in a new invoice or invoice items. Only minor attributes, like metadata or default_payment_method, can be updated on such subscriptions.:

The status of a subscription can't be access or changed via the API. I guess I'd have to create a new one and offer the possibility to keep monthly payments or single payment ?

Any idea or good practice in this case ?

MYSQL server get CPU utilization 100% while running on Redmine Application in ubuntu [closed]

When we  click on "Spent time" on redmine application, the cpu utilisation of mysql server goes to 100%  and the whole system hangs.  What is the possible solution for this App Server - Config (Ubuntu 20.01 - Rails version- 2.7, Redmine version-5.0.1 , vCPUs 2 and Instance type-t2 medium

files been loading in the application: 250 Users 1200 projects 32000 Issues 180000 time logs

samedi 8 avril 2023

Methods like create, update working on the console but not in the veiw

I am a very beginner in Ruby, I am following that Michael Hartl tutorial for toy app, the create user method is wrking fine on console but not on web app,

Tell me any solution

I am a complete beginner

vendredi 7 avril 2023

Loop over more than one hash key in ruby

I have a usecase where I am looping over the array of values from hash using key as shown in the below code. I am creating object based on @params key and returning, because in request I am either getting params[:internal], params[:external] or params[:email]

def create_users
    if @params['internal'].present?
      return @params['internal'].map do |id|
        User.new(type: :internal, user: find_employee(id))
      end
    elsif @params['external'].present?
      return @params['external'].map do |id|
        User.new(type: :external, contact: find_person(id))
      end
    elsif @params['emails'].present?
      return @params['emails'].map do |email|
        User.new(type: :external, contact: contact: fetch_or_create(email))
      end
    end
  end

However, now my usecase has changed and now in request I might get params[:internal] or params[:external], params[:email] both together.

My ask here is, if in request I get params[:external], params[:email] both, would it be possible to do something like that:

return @params['external','email'].map do |id|
        User.new(type: :external, contact: find_person(id))
        User.new(type: :external, contact: contact: fetch_or_create(email))
      end

However there is a possibility that only params[:external] or params[:email] is present in request. So for these cases, handling should also be done.

I am calling this method UserForm.new(params, user).create_users and initialising the object :

def initialize(parameter_hash, user)
    @params = parameter_hash
    @user = user
  end

Any help would be appreciated here, since I am new to ruby so exploring ways here to find the best solution.

jeudi 6 avril 2023

ruby - validates if empty string or is a number

I want to validate if a received param is either an empty string or a positive number, i tried with:

validates :my_flield, presence: true, if: -> {((my_flield.is_a? String) && my_flield.empty?) || ((my_flield.is_a? Numeric) && my_flield>0) }

but it doesn't work. I can still either put non empty strings and negative values. How should i do it?

A ruby validation that works