ruby – After upgrading JAVA, my tests in jruby stopped working because java was no longer found

I updated JAVA to jre1.8.0_221. My JAVA_HOME will also be changed to the correct new location, but intelliJ will display the message: "The Java installation specified by JAVA_HOME can not be found.

I have checked the project settings in IntelliJ: Project SDK is set correctly, module is set correctly. Platform settings: SDKs are defined.

ruby – dynamically combine ActiveRecord Relation results

This is not the actual use case, but for the sake of simplicity we assume I have an ActiveRecord animal model in a Rails app. The animals have one name (string) and rating (Int). There could be animals with the same name but different ratings. In my animal model, I have a hard-coded constant like this:

SPECIAL_ANIMAL_TYPES = (
  { name: 'Cat', rating: 3 },
  { name: 'Dog', rating: 5 },
  { name: 'Fish', rating: 1 }
)

I would like to retrieve a single ActiveRecord: relation with all animals that meet these attributes exactly, I can not pass an array to that where Clause like where(name: ('Cat', 'Dog', etc), rating: (3, 5, 1)) because I only want cats with rating 3 and dogs with rating 5 and so on. As I said earlier, there may be multiple records with the same name but different ratings.

In the animal model, I have a class method (basically an area) to capture the records that match the types specified in SPECIAL_ANIMAL_TYPES. The following code does what I want, but is clearly pretty ugly. If I add more types to SPECIAL_ANIMAL_TYPES, I would have to change this method:

def self.special_animals_only
 where(SPECIAL_ANIMAL_TYPES(0)).or(where(SPECIAL_ANIMAL_TYPES(1))).or(where(SPECIAL_ANIMAL_TYPES(2)))
end

I also tried something like:

def self.special_animals_only
  SPECIAL_ANIMAL_TYPES.collect { |types| where(types) }.sum
end

But that returns an array and I want an ActiveRecord relation. Is there a more elegant way to write this class method so that I can continue to add types to the constant and use that method dynamically?

Ruby on Rails – How to efficiently extract data from a list in RoR?

I have a hash with all the information of a model and want to bring a specific line. I have a process that I am more than certain that is not the most efficient.

ropas = Ropa.all
_id = 4
tomalo = {}
puts "======================"
puts "_id: #{_id}"
ropas.each do |r|
  puts r.inspect
  if r.id == _id
    tomalo = r
  end
end
puts "======================"
puts tomalo.inspect
puts "======================"

And that's the output:

======================
_id: 4
  Ropa Load (0.9ms)  SELECT "ropas".* FROM "ropas"
  ? app/controllers/ropas_controller.rb:38
#

How can I extract the data more efficiently?

Web Development – What is a Ruby "Process"

Sometimes I find terms like "CPU", "threads", "process" etc. when reading documentation or blog posts.

I would like to know what these terms mean, but unfortunately I have not found any material that makes things "baffled". Please note that I know what the academic Definitions for these things are. I still have no idea what they are or how they are tied to web applications.

Today I came across the following:

"The main drawback of using the classic style instead of the
Modular style is that you only have one Sinatra application pro
Ruby process. "

By a dumb person, when I copy my code to my server and execute the appropriate commands to start the application – in this case, one of **ruby app.rb**. **rackup -s thin**. puma -C /path/to/config_fileetc. – I assume that only one Sinatra application is running. The cited statement implies that it is possible to have more than one ruby ​​process.

Can someone please explain to me what a Ruby process is? It would be very grateful if the explanation could be linked to the way cmds wish it **RAILS_ENV=production rails s** or **ruby app.rb** Perform more than 1 ruby ​​process.

ruby – Finds the rotation point of a sorted array that has been "rotated"

This problem comes from part of a LeetCode solution for rotated arrays.

Suppose an array sorted in ascending order is rotated by a specific pivot point
previously unknown.

(ie. (2, 3, 5, 6, 7, 8, 12) could be (6, 7, 8, 12, 2, 3, 5)).

(And we just want to find here the "rotation point" which is 4 because nums(4) is 2 in the array, which we call "rotation point" here)

You can assume that there is no duplicate in the array.

The runtime complexity of your algorithm must be in the order of: $$ O ( log n) $$

I've just used the standard binary search technique, but for some reason I'm not so confident that the following can deliver the right result all the time. For example, the following code version 2 actually contains at least one error, which, however, is not obvious.

Can the code be changed to make it safer to use the standard binary search?

Code 1:

def find_rotation_point(nums)

    # Invariants: 
    #   The rotation point is always in (low, high).
    #   The rotation point is the first beginning index of a sorted sequence.
    #   The range (low, high) always shrinks per each iteration.

    low = 0
    high = nums.length - 1

    while low <= high
        mid = low + (high - low) / 2
        if (mid - 1 >= 0 && nums(mid) < nums(mid - 1))
            return mid
        elsif nums(mid) < nums(0)
            high = mid - 1
        else 
            low = mid + 1
        end
    end
    return 0  # not rotated
end

Code version 2 (Warning: incorrect, but not obvious):

def find_rotation_point(nums)
    low = 0
    high = nums.length - 1

    while low <= high
        mid = low + (high - low) / 2
        if (mid - 1 >= 0 && nums(mid) < nums(mid - 1))
            return mid
        elsif nums(mid) > nums(0)   # these 4 lines different from version 1
            low = mid + 1
        else 
            high = mid - 1
        end
    end
    return 0  # not rotated
end

ruby – Calculates the percentage of the sum of hash values

Please check my code and help on How can I improve the calculation in the method and class definition with SOLID Ruby principles?

The application has a static JSON file that contains:

{
  "homes": {
    "person_a": "windows+tables",
    "person_b": "lights+tables",
    "person_c": "doors+curtains"
 }
}

The application should calculate quotes for the 3 insurers for each user request. The business requirement is as follows:

The offer is 10% of the rate if 2 covers match, or 20% if only 1 cover matches, and that's the biggest requirement, 25% if it's the second largest, or 30% if it's the third.

The user's request is as follows

{:curtains=>20, :tables=>30, :windows=>50}

The system should not return an offer if the value is zero (0).

For example: The application returns the result for the above user request

{
    person_a: 8 (10% of 80 (two matches on windows and tables))
    person_b: 7.5 (25% of 30 (one match on tables, the 2nd biggest cover))
    insurer_c: 6 (30% of 20 (one match on curtains, the 3rd biggest cover)

}

That's my solution:


require_relative './rules'

module Coverage
  class CalculateQuotes
    def initialize(quotes)
      @quotes = quotes
    end

    def get_rates
      result = ()
      @insurer = Coverage::Rules.parse_file ## which will give {
                                        #"insurer_rates": {
                                       #"person_a": "windows+tables",
                                       # "person_b": "lights+tables",
                                       #"person_c": "doors+curtains"
                                      # }}
      @insurer(:insurer_rates).each do |k, v|
        @match_covers = match_cover(v.split("+"))
        result << (k, calculate_rate )
      end
    end

    def match_cover(covers)
      covers = covers.map { |x| x.to_sym }
      @quotes.select { |k,v| covers.include?(k) }
    end

    def calculate_rate
      premium    = 0.0
      persentage = get_percentage_by_match_covers
      @match_covers.values.each do |v|
        premium += v * persentage
      end
      premium == 0 ? nil : premium
    end

    def get_percentage_by_match_covers
      if @match_covers.size == 2
        0.1
      elsif @match_covers.size == 1
        only_1_match_covers
      else
        0
      end
    end

    def only_1_match_covers
      index = position_of_customer_request
      case index
      when 0
        0.2
      when 1
        0.25
      when 2
        0.3
      else
        raise StandardError
      end
    end

    def position_of_customer_request
      (@quotes.to_a.reverse).index(@match_covers.to_a.flatten)
    end
  end
end


request = {:windows=>50, :contents=>30, :engine=>20}

Coverage::CalculateQuotes.new(request).get_rates
````

IoC understand: What exactly does the code written in Ruby do?

I tried to see the difference between a library and a framework. And from one of the posts it became clear that the biggest difference is the reversal of control, d. H., where framework calls your code.

Martin Fowler's article on IoC seems to be pretty good, unless it's in ruby ​​language that I do not know. What exactly does the following code do?

  require 'tk'
  root = TkRoot.new()
  name_label = TkLabel.new() {text "What is Your Name?"}
  name_label.pack
  name = TkEntry.new(root).pack
  name.bind("FocusOut") {process_name(name)}
  quest_label = TkLabel.new() {text "What is Your Quest?"}
  quest_label.pack
  quest = TkEntry.new(root).pack
  quest.bind("FocusOut") {process_quest(quest)}
  Tk.mainloop()

My understanding If the code flow is event-driven, or generally whenever .NET functions such as anonymous types, extension methods, lambda expressions, etc. are used, the inversion of the controller can be detected

Ruby on Rails – Why does my view display instances when they are not invoked?

When I go to an index view for my Rails program, it is assumed that all object properties are traversed and displayed one after the other. My program does it perfectly as expected.

An array of each instance will also appear below the normal list. I'm not sure why. Any thoughts?

In the controller:


def index
  @user = User.find(params(:user_id))
  @characters = @user.characters.all
end

In the view

<%= @characters.each do |char| %>
  <%= char.name %>
<% end %>

What is displayed on the screen from above:

Joe Jane (#, #)

I expect that the index page for the characters of a user will only be displayed

JoeJane

Currently it actually shows:

Joe Jane (#Character id: 1, Allies: "None", Enemies: "None", Description: "Something", user_id: 6, race_id: 1, created_at: "2019-08-11 08:37:08", updated_at: "2019-08-11 08:37:08", name: "Joe">, #Character id: 2, allied: "none", enemies: "none", description: "something", user_id: 6, race_id: 1, created_at: "2019-08-11 08:39:49", updated_at: "2019-08-11 08:39:49", name: "Jane">)

The program seems to be with me at all. I took out the char.name part and just executed a blank block and got the same result as above, minus the Joe Jane bit. I reset my server, deleted it from the database and reloaded it, and compared it with similar code I used in other projects that do not get these weird results. I am not sure what causes this curiosity.