Question

Code in question:

class Model < ActiveRecord::Base

    require 'Library'
    AN_ARRAY = [ 1, 2 ]
    THING = Classname.new.thing()

    def self.perform(param)
        # do stuff using THING, i.e. THING.do(something)
        do_things(param)
    end

    def self.do_things(param)
        # do stuff with AN_ARRAY and/or THING
    end

end

I'm not quite sure how Rails handles models. Do the top three statements execute only once? Is there only one THING, or might there be many THINGs? If I queue workers to execute self.perform(), will things be alright as long as the state of THING isn't changed? Should I be initializing THING in the functions themselves instead? Thanks.

Was it helpful?

Solution

When the class is loaded, all the lines are evaluated by ruby once:

The following two lines define two constants since they begin with a capital letter. This means there is only one THING and one AN_ARRAY.

    AN_ARRAY = [ 1, 2 ]
    THING = Classname.new.thing()

The def statements below are also evaluated once and end up defining two class methods:

    def self.perform(param)
        # do stuff using THING, i.e. THING.do(something)
        do_things(param)
    end

    def self.do_things(param)
        # do stuff with AN_ARRAY and/or THING
    end

So, the methods should work as expected in your queue workers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top