Class Extension Mixin

E

Eugen Ciur

Hi

I want to buid up module of Financial variables.
It can be used like this
Financial.year.start #returns start of ... guess what :)
Financial.year.finish
Financial.quarter.start
Financial.quarter.end

...
You got the idea. It must be easily extensible.
Here is what I came up with:

#!/usr/lib/ruby

module FinancialYear
def year
EndPoint.new
end
class EndPoint
def start
@start = "01/01/"+Time.now.strftime("%Y")
end
def finish
@finish = "31/12/"+Time.now.strftime("%Y")
end
end
end

module Period
def self.included(base)
base.extend(FinancialYear)
end
end

module Financial
include Period
end


I used mostly idioms from Metaprogramming Ruby - Class Extension Mixin
Any suggestion for improvement ?
I am novice in ruby so any suggestion is welcome !
 
P

Paolo \Nusco\ Perrotta

I used mostly idioms from Metaprogramming Ruby - Class Extension Mixin
Any suggestion for improvement ?

The point of a Class Extension Mixin is that you can use to get both
class methods and instance methods with a single include(). If you
only have class methods, you can also use a simple extend() in the
inclusor.

For something as simple as your example, even that might be overkill.
Unless you have a specific reason to decouple the year() method by
putting it in a separate module, you might be better off just defining
it as a class method of Financial:

class EndPoint
def start
@start = "01/01/"+Time.now.strftime("%Y")
end
def finish
@finish = "31/12/"+Time.now.strftime("%Y")
end
end

module Financial
def self.year
EndPoint.new
end
end

Financial.year.start # => "01/01/2010"
Financial.year.finish # => "31/12/2010"

Paolo Perrotta
Metaprogramming Ruby (http://www.pragprog.com/titles/ppmetr)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top