ruby on rails - Accessing instance method from class method -
i have rails 4 app has alert model , tests associated each alert.
when new alert created have after_create filter uses instance method create new test:
class alert < activerecord::base has_many :tests after_create :create_test private def create_test #bunch of code using external api data test.create end end
i have cron job want use create new test each alert. plan have class method that:
def self.scheduled_test_creation @alerts = alert.all @alerts.each |a| a.create_test end end
that won't work because instance method private. know can around using send example. or can make methods public. or can rewrite bunch of api code in instance method.
i not sure best way be. don't want write same code twice , want make sure practice. maybe in case methods don't have private - know difference between public/private/protected don't understand when methods should private/protected.
any appreciated
i service classes interactions between multiple models. callbacks can make logic quite hard follow.
eg:
class alertcreator def initialize(alert) @alert = alert end def call if @alert.save alert_test = testbuilder.new(@alert).call alert_test.save true end end end class testbuilder def initialize(alert) @alert = alert end def call # external api interaction stuff # return unsaved test end end
inside controller, you'd call alertcreator.new(@alert).call
instead of usual @alert.save
.
Comments
Post a Comment