I have 3 models:
Class Model1
end
Class Model2
end
Class Model3
end
I have this code:
scope :created_between, lambda { |start_time, end_time| where(:created_at => (start_time...end_time)) }
class << self
## Class methods for calculating searches
def created_today
today = Time.zone.now
created_between(today.beginning_of_day, today.end_of_day)
end
def created_yesterday
yesterday = Time.zone.now - 1.day
created_between(yesterday.beginning_of_day, yesterday.end_of_day)
end
def created_last_week
start_time = (Time.zone.now - 1.week).beginning_of_day
end_time = Time.zone.now
created_between(start_time, end_time)
end
def created_last_month
start_time = (Time.zone.now - 1.month).beginning_of_day
end_time = Time.zone.now
created_between(start_time, end_time)
end
def created_last_year
start_time = (Time.zone.now - 1.year).beginning_of_day
end_time = Time.zone.now
created_between(start_time, end_time)
end
end
I need add this code to 3 models but I don't want repeat the code inside each model.
How can I do it?
Thank you very much!
Try this:
module CommonClassFunctions
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
## Class methods for calculating searches
def created_today
today = Time.zone.now
created_between(today.beginning_of_day, today.end_of_day)
end
def created_yesterday
yesterday = Time.zone.now - 1.day
created_between(yesterday.beginning_of_day, yesterday.end_of_day)
end
def created_last_week
start_time = (Time.zone.now - 1.week).beginning_of_day
end_time = Time.zone.now
created_between(start_time, end_time)
end
def created_last_month
start_time = (Time.zone.now - 1.month).beginning_of_day
end_time = Time.zone.now
created_between(start_time, end_time)
end
def created_last_year
start_time = (Time.zone.now - 1.year).beginning_of_day
end_time = Time.zone.now
created_between(start_time, end_time)
end
end
end
Class Model1
include CommonClassFunctions
end
Class Model2
include CommonClassFunctions
end
Class Model3
include CommonClassFunctions
end
You can define a module with this methods, then include it on the 3 models.
Like :
module Searcheable
def created_today
.
.
.
.
.
end
end
Then on the classes:
class Model1
extend Searcheable
end
class Model2
extend Searcheable
end
class Model3
extend Searcheable
end
you can do this with inheritance
class Model
class << self
def created_today
puts "created today from Model"
end
end
end
class Model1 < Model
end
class Model2 < Model
end
class Model3 < Model
end
Model1.created_today
# output: created today from Model
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.