Module: FmtAlias::Aliases::ClassMethods
- Defined in:
- lib/fmt_alias/aliases.rb
Instance Method Summary collapse
- #date_fmt_alias(attr, fmt, *args) ⇒ Object
- #define_alias_for(attr, getter, setter, *args) ⇒ Object
- #split_alias(attr, *args) ⇒ Object
Instance Method Details
#date_fmt_alias(attr, fmt, *args) ⇒ Object
21 22 23 24 25 26 27 28 |
# File 'lib/fmt_alias/aliases.rb', line 21 def date_fmt_alias(attr, fmt, *args) define_alias_for( attr, proc { send(attr).strftime(fmt) unless send(attr).nil? }, proc { |value| send(:"#{attr}=", (Time.parse(value, fmt) rescue nil)) }, *args ) end |
#define_alias_for(attr, getter, setter, *args) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/fmt_alias/aliases.rb', line 13 def define_alias_for(attr, getter, setter, *args) = args. name = .delete(:name) || "#{attr}_fmt" define_method name, &getter define_method "#{name}=", &setter end |
#split_alias(attr, *args) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/fmt_alias/aliases.rb', line 30 def split_alias(attr, *args) = args. polymorphic = .delete(:polymorphic) attrs = .delete(:attrs) delim = .delete(:delimiter) || ':' raise ArgumentError, "Specify :polymorphic or :attrs option for split_alias :#{attr} in #{self.name}" if attrs.blank? && polymorphic.blank? if polymorphic attrs = ["#{attr}_type", "#{attr}_id"] [:name] ||= "#{attr}_type_id" else [:name] ||= "#{attr}_split" end define_alias_for( attr, proc { r = attrs.map { |a| send(a) }.compact r.present? ? r.join(delim) : nil }, proc { |value| values = value.to_s.split(delim) h = Hash[attrs.zip(values)] h.map { |a, v| send("#{a}=", v) } }, ) end |