Fellow Stranger
Fellow Stranger

Reputation: 34023

Access object attribute inside module

I have a class with the attribute .weekday saved as an integer value.

I'm trying to create a method in a module that converts that numeric value to the corresponding weekday.

This is how I like to work:

MyClass.weekday
=> 2
MyClass.weekday.my_module_method
=> "Tuesday"

Is it possible to do this conversion with a module method or am I thinking wrong here?

I can access the object from within the module mehtod, by self, but I don't seem to be able to do self.weekday.

Upvotes: 0

Views: 717

Answers (1)

Alex.Bullard
Alex.Bullard

Reputation: 5563

What you are trying to do is certainly possible. You are correct when you point to ActiveRecord::Inflector as something that works similarly. This approach modifies the Fixnum class itself to add new methods and although I don't generally recommend ad-hoc patching of core classes, you can see it in action in active_support/core_ext/integer/inflections.rb :

require 'active_support/inflector'

class Integer
  # Ordinalize turns a number into an ordinal string used to denote the
  # position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
  #
  #  1.ordinalize     # => "1st"
  #  2.ordinalize     # => "2nd"
  #  1002.ordinalize  # => "1002nd"
  #  1003.ordinalize  # => "1003rd"
  #  -11.ordinalize   # => "-11th"
  #  -1001.ordinalize # => "-1001st"
  #
  def ordinalize
    ActiveSupport::Inflector.ordinalize(self)
  end
end

In your case I might do something like:

module WeekdayInflector
  def weekday
    Date::DAYNAMES[self]
  end
end


class Fixnum
  include WeekdayInflector
end

which will at least help others track down the methods you added by looking at the module. Please note that this will affect ALL instances of Fixnum and could lead to conflicts if you include a Gem that tries to do the same thing. It is worth asking whether this tradeoff is worth it or if defining a simple view helper is the better way to go.

Upvotes: 1

Related Questions