Use find to initialize a constant?

Something like that:

class Category

   SOME_CATEGORY = find_by_name("some category")

end

Category :: SOME_CATEGORY
tried without problems, but I want to know if this is a bad idea, and the reasons if they are ..

thanks

0
source share
3 answers

If you do not want to hit the database every time you have to cache the model. There are several ways to do this, but one quick way is Memoization . This was introduced in Rails 2.2.

class Category < ActiveRecord::Base
  class << self
    extend ActiveSupport::Memoizable
    def named(name)
      find_by_name(name)
    end
    memoize :named
  end
end

Use it like that.

Category.named("some category") # hits the database
Category.named("some category") # doesn't hit the database

The cache must remain constant in all requests. You can reset the cache by passing trueas the last parameter.

Category.named("some category", true) # force hitting the database
+6
source

What do you want to do?

May be:

class Category
  def self.some_category
    Category.find_by_name("some category")
  end
end

So you can call:

Category.some_category
=> <Category#2....>
0

, . , Rails -. -, . ALL_CAPS_WORDS Ruby ++. Bleah.

, . ? , Rails, , ?

, DB, , , Lichtamberg:

def self.method_missing(category, *args)  # The 'self' makes this a class method
  @categories ||= {}
  if (@categories[category] = find_by_name(category.to_s))
    class_eval "def self.#{category.to_s}; @categories[#{category}]; end" 
    return @categories[category]
  end
  super
end

, , Category.ham, , find_by_name("ham"), , method_missing() . OpenStruct, BTW; , .

(Of course, you still risk that, since they are all stored in memory, your Rails application will not reflect any changes you make to your category objects. This suggests that the changes will not occur, is it really important to you to determine if this is really an assumption for your application, you can always put a callback after_updatein your code that resets @@categoriesif this is a problem, but at this point it starts to get complicated.)

0
source

Source: https://habr.com/ru/post/1714238/


All Articles