ruby - Add a Business logic class to another model in Rails -
i've been given assignment i'm totally stuck on.
i've got 2 classes:
#/app/models/numbers.rb class numbers < activerecord::base # model has(:id, :list_length, :number_list) # array of integers serialize :number_list #generate number list def create_list array.new(self.list_length).map!{rand(100)} end def initialize(*params) super if !params.compact.empty? self.number_list = create_list end end end and:
#/lib/update.rb class update #takes array of integers def initialize(num_list) @num_list = num_list end def add_rand to_add = rand(10) @num_list.each{|n| n += to_add} end def get_list @num_list end end so, update has remain library class need able instantiate numbers object , call update class methods on update num_list attribute.
so after creating numbers object, let's call @num_obj, need call @num_obj.add_rand , save updated @num_obj.num_list array database.
i'm allowed add helpers , modules like. after hours , hours of bashing away @ i'm totally lost , i'm sure it's simple haven't learned yet (and overlooked in hours of searching). point me in right direction?
edit: after more reading , couple of suggestions, changed num_list in numbers class numbers_list make things clearer
i added module:
#/lib/num.rb module num def add_rand temp = update.new(self.number_list) self.number_list = temp.add_rand end def get_list temp = update.new(self.number_list) temp.get_list end end and add 'include num' numbers class.
now can take numbers object , call update methods on it. works, i'm not sure if there's more elegant way it....
edit: turns out isn't right, either. gotta have update persist somehow get_list method returns update's num_list
it sounds trying separate active record model how update (business logic). might want take @ using decorator pattern:
class numberupdatedecorator < simpledelegator def add_rand number_list.each { |number| number += rand(10) } save! end end the usage in code:
numbers.find_each |number| numberupdatedecorator.new(number).add_rand end also, might simplify things change numbers class number. add numbercollection model has many numbers. way not dealing trying serialize / deserialize list.
Comments
Post a Comment