Reputation: 84
I tried to to use concerns in my project. I would like to build a method to get the date in french for every model I have. Here is my code. Currently, I get the error : wrong argument type Class (expected Module) at the line include DateTime in the model.
Here is my file models/concerns/date_time.rb
module DateTime
extend ActiveSupport::Concern
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
# methods defined here are going to extend the class, not the instance of it
module ClassMethods
def date_string
h = {1=>'Janvier',2=>'Février',3=>'Mars',4=>'Avril',5=>'Mai',6=>'Juin',7=>'Juillet',8=>'Août',9=>'Septembre',10=>'Octobre',11=>'Novembre',12=>'Décembre'}
"#{self.created_at.day}-#{h[self.created_at.month]}-#{self.created_at.year}"
end
end
end
Here is my file models/demands.rb
class Demand < ActiveRecord::Base
include DateTime
belongs_to :skill
belongs_to :project
belongs_to :user
has_many :transactions
validates :project, presence: true
validates :skill, presence: true
validates :title, presence: true
end
Thanks in advance for your help !
Upvotes: 0
Views: 172
Reputation: 7522
Your immediate issue here is that, because DateTime
is a class in the Ruby standard library, Ruby is trying to include that class, not your module. If you rename the module to something unique, say, UsesDateTime
, your error should go away.
That said, for this particular method, I agree with max.
Upvotes: 2
Reputation: 102046
Use the Rails built in I18n functionality instead. Doing localization in the model layer is just wrong. Models should only be concerned with data and business logic - not how data (like dates) are presented.
Upvotes: 2