[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Factory design

Claus Spitzer

4/11/2005 9:56:00 PM

Greetings!
A friend of mine has recently started using Ruby, and has run into a
little problem. He is trying to create different objects depending on
the contents of a string. His intuition is to use factory design for
this, and he'd like to know if there is a Ruby Way to do this.

Below is his original e-mail.
Regards...
-CWS

----8<----
Hello, I'm wondering if anyone can suggest a good Ruby idiom for the
following problem. I'm pretty new to Ruby and am migrating from
statically-typed languages like Java and C++.


I have a string representation of some data that I want to read from an input
source and load into a file. Based on what this input is, I want to create a
subclass.

The concrete example is that I have a number of "events" in a log file that I
want to be able to create based on the input I read. There are three kinds
of events: a Phase, an Interruption, and a Defect. Each one of them has a
beginning time, a duration, and a comment.

Phases can contain Interruptions and Defects. Defects can contain
Interruptions and other Defects.


In any case, I have an identifier on my log file that looks like "2005-01-04
23:34:12 begin_phase". If I see this, I want to create a "Phase" object. If
it says "2005-01-04 23:52:16 begin_interruption", then I want to create an
interruption instead.

My intuition is that this is a typical Factory Design Pattern, so I would
create a Ruby class method that creates the appropriate type based on the
results of the string and returns it. However, someone familiar with Ruby
told me that Ruby's dynamic typing and duck typing is such that this kind of
solution "feels incorrect".

Does anyone have suggestions as to what I can do? Thanks!

-- -- Irwin (ihkwan at gmail.com)


18 Answers

James Gray

4/11/2005 10:06:00 PM

0

On Apr 11, 2005, at 4:56 PM, Claus Spitzer wrote:

> Greetings!
> A friend of mine has recently started using Ruby, and has run into a
> little problem. He is trying to create different objects depending on
> the contents of a string. His intuition is to use factory design for
> this, and he'd like to know if there is a Ruby Way to do this.

Generally, Ruby makes this kind of design trivial with the fact that
classes are objects. Just pass the class object, it's a free factory!
Here's an example:

class PrinterA
def print_something_very_cool
puts "Using PrinterA!"
end
end

class PrinterB
def print_something_very_cool
puts "Using PrinterB!"
end
end

def engage_printer( printer )
p = printer.new
p.print_something_very_cool
end

engage_printer PrinterA
engage_printer PrinterB

Hope that helps.

James Edward Gray II



Assaph Mehr

4/11/2005 10:19:00 PM

0


> In any case, I have an identifier on my log file that looks like
"2005-01-04
> 23:34:12 begin_phase". If I see this, I want to create a "Phase"
object. If
> it says "2005-01-04 23:52:16 begin_interruption", then I want to
create an
> interruption instead.

All class objects are kept as constants of Object. In fact when you
write a class name in your script Ruby treats it like any other
constant (starts with a capital letters) - it's just in Object name
space so every object can access it. Thus you can get them like any
other constant in your script:

c:\>irb
irb(main):001:0> class Phase; end
=> nil
irb(main):002:0> s = "2005-01-04 23:34:12 begin_phase"
=> "2005-01-04 23:34:12 begin_phase"
irb(main):003:0> klass_name = s.match(/begin_(\w+)/).captures[0] rescue
nil
=> "phase"
irb(main):006:0> klass = Object.const_get(klass_name.capitalize) if
klass_name
=> Phase
irb(main):007:0> o = klass.new
=> #<Phase:0x2d5f1b0>

As a further note, when you come to use the klass variable at runtime
remember that case statements use the #=== method which is slightly
different for Class objects - it tests if an object is an instance of
the the class:

case klass
when Phase
puts 'new phase'

when Object
puts 'something else'
end

Will print: 'something else'.
You need something like:

case klass.name
when 'Phase'
puts 'new phase'

when 'Object'
puts 'something else'
end

Which will print: 'new phase'.

HTH,
Assaph

dblack

4/11/2005 10:23:00 PM

0

Nicholas Seckar

4/11/2005 10:50:00 PM

0

A more complex, but still simple example:

class Microwave # defrosts food
attr_accessor :creators
def initialize()
@creators = []
end
def mode(key = nil, cls = nil)
delegate = cls ? (Proc.new {|path| cls.new(path)}) : Proc.new
creators << [key, delegate]
end

def defrost(path)
r = nil
creators.each do |(key, delegate)|
next unless (case key
when nil then true
when Regexp then key =~ path
when String then key == path
else false
end)
return r if (r = delegate.call(path))
end
end
end

# A delectable bit wrap. Whole wheat pita!
class FileWrap
attr_accessor :contents
def initialize(path)
@path = path
@contents = IO.read(path)
end
def method_missing(sel, *args)
r = @contents.send(sel, *args)
if sel.to_s[-1..-1] == '!'
(File.open(@path, 'w') {|f| f.write(@contents)})
end
r
end
end

M = Microwave.new

M.mode(/\.txt$/, FileWrap)
M.mode(/\.ruby_object$/) {|path| Marshal.load(IO.read(path))}

# Put some stuff in the fridge
File.open('/tmp/a_hash.ruby_object', 'w') do |f|
f.write(Marshal.dump(:a => 2, 'a' => 'two'))
end
File.open('/tmp/a_file.txt', 'w') do |f|
f.write('Hello World')
end

h = M.defrost('/tmp/a_hash.ruby_object')
puts h['a'] #=> two
puts h[:a] #=> 2

f = M.defrost('/tmp/a_file.txt')
puts f.contents #=> Hello World
f.gsub!('World', 'Food')
puts `cat /tmp/a_file.txt` #=> Hello Food

Well, it was simple. Then I became carried away.

--

Nicholas Seckar aka. Ulysses


Claus Spitzer

4/11/2005 11:03:00 PM

0

Thanks to everyone who replied - My friend really appreciates the help.
Cheers!

On Apr 11, 2005 6:50 PM, Nicholas Seckar <nseckar@gmail.com> wrote:
> A more complex, but still simple example:
>
> class Microwave # defrosts food
> attr_accessor :creators
> def initialize()
> @creators = []
> end
> def mode(key = nil, cls = nil)
> delegate = cls ? (Proc.new {|path| cls.new(path)}) : Proc.new
> creators << [key, delegate]
> end
>
> def defrost(path)
> r = nil
> creators.each do |(key, delegate)|
> next unless (case key
> when nil then true
> when Regexp then key =~ path
> when String then key == path
> else false
> end)
> return r if (r = delegate.call(path))
> end
> end
> end
>
> # A delectable bit wrap. Whole wheat pita!
> class FileWrap
> attr_accessor :contents
> def initialize(path)
> @path = path
> @contents = IO.read(path)
> end
> def method_missing(sel, *args)
> r = @contents.send(sel, *args)
> if sel.to_s[-1..-1] == '!'
> (File.open(@path, 'w') {|f| f.write(@contents)})
> end
> r
> end
> end
>
> M = Microwave.new
>
> M.mode(/\.txt$/, FileWrap)
> M.mode(/\.ruby_object$/) {|path| Marshal.load(IO.read(path))}
>
> # Put some stuff in the fridge
> File.open('/tmp/a_hash.ruby_object', 'w') do |f|
> f.write(Marshal.dump(:a => 2, 'a' => 'two'))
> end
> File.open('/tmp/a_file.txt', 'w') do |f|
> f.write('Hello World')
> end
>
> h = M.defrost('/tmp/a_hash.ruby_object')
> puts h['a'] #=> two
> puts h[:a] #=> 2
>
> f = M.defrost('/tmp/a_file.txt')
> puts f.contents #=> Hello World
> f.gsub!('World', 'Food')
> puts `cat /tmp/a_file.txt` #=> Hello Food
>
> Well, it was simple. Then I became carried away.
>
> --
>
> Nicholas Seckar aka. Ulysses
>
>


nobu.nokada

4/11/2005 11:32:00 PM

0

Hi,

At Tue, 12 Apr 2005 06:56:09 +0900,
Claus Spitzer wrote in [ruby-talk:137841]:
> A friend of mine has recently started using Ruby, and has run into a
> little problem. He is trying to create different objects depending on
> the contents of a string. His intuition is to use factory design for
> this, and he'd like to know if there is a Ruby Way to do this.

I remember that I'd written this library and posted somewhere
once.


module Factory
def factory(c = Proc.new)
(@__factory ||= []) << c
end

def create(*args)
n = args.size
@__factory.reverse_each do |f|
next if (a = f.arity) < 0 ? n < ~a : n != a
return f if f = f.call(*args)
end if defined?(@__factory)
nil
end

def inherited(klass)
factory(klass.method(:create))
super(klass)
end
end

if $0 == __FILE__
class A
extend Factory

def initialize(obj)
@obj = obj
end

factory(method(:new))
end

class B < A
factory do |obj|
new(obj) if obj.respond_to?(:split)
end
end
class B1 < B
factory do |obj|
new(obj) if obj.respond_to?(:string)
end
end
class C < A
factory do |obj|
new(obj) if obj.respond_to?(:readline)
end
end

p A.create("")
require 'stringio'
s = StringIO.new
p A.create(s)
p B.create(s)
end


--
Nobu Nakada


Robert Klemme

4/12/2005 7:12:00 AM

0


"David A. Black" <dblack@wobblini.net> schrieb im Newsbeitrag
news:Pine.LNX.4.61.0504111508240.7304@wobblini...
> Hi --
>
> On Tue, 12 Apr 2005, Claus Spitzer wrote:
>
> > Greetings!
> > A friend of mine has recently started using Ruby, and has run into a
> > little problem. He is trying to create different objects depending on
> > the contents of a string. His intuition is to use factory design for
> > this, and he'd like to know if there is a Ruby Way to do this.
> >
> > Below is his original e-mail.
> > Regards...
> > -CWS
> >
> > ----8<----
> >
> > In any case, I have an identifier on my log file that looks like
"2005-01-04
> > 23:34:12 begin_phase". If I see this, I want to create a "Phase"
object. If
> > it says "2005-01-04 23:52:16 begin_interruption", then I want to
create an
> > interruption instead.
> >
> > My intuition is that this is a typical Factory Design Pattern, so I
would
> > create a Ruby class method that creates the appropriate type based on
the
> > results of the string and returns it. However, someone familiar with
Ruby
> > told me that Ruby's dynamic typing and duck typing is such that this
kind of
> > solution "feels incorrect".
> >
> > Does anyone have suggestions as to what I can do? Thanks!
>
> I wouldn't worry about the matter of duck typing here. The concept of
> duck typing, as I understand it, is essentially an explanatory tool
> for getting people to understand, visualize, and make use of the fact
> that class and type are not the same as each other in Ruby (a fact
> that can be summed up very quickly but that in fact has huge
> ramifications). Duck typing doesn't mean you never instantiate
> objects of a particular class, nor that you never parse a string :-)
>
> For this project, I don't think any (webbed) toes will be stepped on
> if you do something like:
>
> require 'scanf'
>
> File.open("input.dat") do |fh|
> fh.scanf("%d-%d-%d %d:%d:%d begin_%s") do |y,mo,d,h,mi,s,klass|
> c = Object.const_get(klass.capitalize).new
> # etc.
> end
> end
>
> (to illustrate with a simple line-by-line treatment).

If one needs more flexibility (for example because several tags should
create instances of the same class or whatever) then a hash in between
serves well:

FACTORIES = {
"phase" => Phase,
"interruption" => Interruption,
# ...
}

if /begin_(\w+)/ =~ line
obj = FACTORIES[$1].new
end

Or, even more flexible

FACTORIES = {
"phase" => lambda {|line| Phase.new line},
"interruption" => lambda {|*| Interruption.new},
# ...
}

if /begin_(\w+)/ =~ line
obj = FACTORIES[$1].call line
end

Kind regards

robert

yansimon52

11/17/2010 4:39:00 PM

0

On Nov 17, 11:20 pm, The Cynic <i.thecy...@gmail.com> wrote:
> On Nov 17, 8:27 pm, darion <hyda...@hotmail.com> wrote:
>
>
>
>
>
> > On Nov 16, 4:04 pm, yansimon52 <yansimo...@hotmail.com> wrote:
>
> > > On Nov 16, 9:47 pm, Paul Saccani <sacc...@omen.net.au> wrote:
>
> > > > On Sun, 14 Nov 2010 21:43:31 -0800 (PST), yansimon52
>
> > > > <yansimo...@hotmail.com> wrote:
> > > > >On Nov 12, 2:06 pm, Paul Saccani <sacc...@omen.net.au> wrote:
> > > > >> On Thu, 11 Nov 2010 10:05:32 -0800 (PST), rst0wxyz
>
> > > > >> <rst0w...@yahoo.com> wrote:
> > > > >> >> This Darion guy...he is defending suicide bombers,
> > > > >> >> telling us Muslims are not terrorist, not killers as if
>
> > > > >> >I have to agree with darion that Muslims have been oppressed and
> > > > >> >mistreated. They are fighting back against injustice done to them by
> > > > >> >American and European countries.
>
> > > > >> Bollocks. It is the same tired argument used by fascists the world
> > > > >> over to justify the indefensible.
>
> > > > >Paul....one can never win an argument with a 'smart alec'....cos,
> > > > >smart alec always come with excuses....always got something to say.....
>
> > > > He *seems* to have given up, surprisingly.  Jokers like this tend to
> > > > use tactics of raising irrelevant matters, playing the fool and trying
> > > > to justify themselves by reference to the sins of others.  Take those
> > > > crutches away from them, and they have a hard time of it.  
>
> > > > I agree that it is hard to "win", because such types are
> > > > constitutionally incapable of admitting error.  However, I do feel
> > > > that it is important to expose them to intense scrutiny from time to
> > > > time, not just for those who might be deceived by them, but also in
> > > > the hope that they themselves might see the light.
> > > > --
> > > > Cheers,
> > > > Paul Saccani
> > > > Perth, Western Australia.- Hide quoted text -
>
> > > > - Show quoted text -
>
> > > We must continue to create awareness on this so-called 'religion of
> > > peace'...LOL...LOL....
>
> > but many agree with formeer Presiden George W. Bush who said in
> > December 2001:
> > “The face of terror is not the true faith of Islam.  That's not what
> > Islam is all about.  Islam is peace.”
>
> "many"? Who are the many? Is it your interpretation?
>
>
>
> > “When we think of Islam we think of a faith that brings comfort to a
> > billion people around the world.  Billions of people find comfort and
> > solace and peace.  And that's made brothers and sisters out of every
> > race -- out of every race.”
>
> Ah! Then he launched the offensive on Iraq. LOL
>
> > > by revealing their flaw religious belief...
>
> > how can you reveal something that is not there?
> > objective teaching has no flaw.
> > it is just impossible.
> > or don't you know it?
>
> What is your definition of "objective: and "subjective" vis-a-vis your
> religion?
>
> > > we do it without having to throw profanity (at their religious belief) on
> > > our arguement.
>
> > whatever method you use, your effort will be futile.
> > because there is no flaw in objective teachng.
>
> > > As for me...I like to reveal its religious flaws in this religious
> > > cult belief of Islam
>
> > yes, cult belief of Islam is all flaw.
> > Islam is no cult. it is not even just religion.
>
> That is your belief. Just like you label other religions as myths, we
> label your belief as a cult. Fair?
> As far as I am concerned, all religions are cults and enclaves of
> superstitious beliefs. Is it not justified that religious fanatics get
> splashed with the same paint they use to tarnish non-believers?
>
>
>
>
>
> > it is submission to Allah, this means that a Muslim also
> > submits, or ought to submit, consciously and deliberately -
> > he must be objective in thought, motive and action.
>
> > objective teaching can not be a cult.
>
> > > ..ie...the difference between the Brightside and
> > > Darkside spiritual forces...
>
> > Islam (genuine religion) is the Brightside
> > and corrupt teaching (made up teaching like Paul's and corrupted
> > Church doctrine) is the Darkside spiritual force.
>
> > > and what's in store for those who continue
> > > to believe this cult belief....it surely change your face's
> > > features...ie. changing one eye's look into squinted eye look...in
> > > some unfortunate muslim elders...-
>
> > yes, just like in HInduism, Chrsitianity, Buddhism, Judaism and
> > Atheism, there are also bad unfortunate leaders among Muslims.
> > don't yo know that too ?
>
> Bravo, you took such a long time to realize this!!!!!- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

Bro Cynic....you are rite on target....this so-called religious belief
of Islam ...yes...its a cult belief afterall..............and this
stupid guy Darion is trying to tell us...'how beautiful Islam
is'..LOL....LOL...

darion

11/17/2010 5:10:00 PM

0

On Nov 17, 4:20 pm, The Cynic <i.thecy...@gmail.com> wrote:

>
> > but many agree with formeer Presiden George W. Bush who said in
> > December 2001:
> > “The face of terror is not the true faith of Islam.  That's not what
> > Islam is all about.  Islam is peace.”
>
> "many"?

yes

> Who are the many?

specially those who support Geoge W. Bush opinion

> Is it your interpretation?

it's a statement of fact.

>
> > “When we think of Islam we think of a faith that brings comfort to a
> > billion people around the world.  Billions of people find comfort and
> > solace and peace.  And that's made brothers and sisters out of every
> > race -- out of every race.”
>
> Ah! Then he launched the offensive on Iraq. LOL

Yes. He is sooooo paranoid of Iraq
that he gone berserk.
the result is millions suffer unecessarily.
and you laugh, because of your fanatic hatred towards Islam/Muslim.

> > > by revealing their flaw religious belief...
>
> > how can you reveal something that is not there?
> > objective teaching has no flaw.
> > it is just impossible.
> > or don't you know it?
>
> What is your definition of "objective: and "subjective" vis-a-vis your
> religion?

to put it simple, objective is everything outside yourself.
subjective is the opposite.
don't you know ?
well now you know a little bit more.

> > > we do it without having to throw profanity (at their religious belief) on
> > > our arguement.
>
> > whatever method you use, your effort will be futile.
> > because there is no flaw in objective teachng.
>
> > > As for me...I like to reveal its religious flaws in this religious
> > > cult belief of Islam
>
> > yes, cult belief of Islam is all flaw.
> > Islam is no cult. it is not even just religion.
>
> That is your belief. Just like you label other religions as myths, we
> label your belief as a cult. Fair?

yes. ok.
and we check it with objective values.
who is wrong.
you or me.

> As far as I am concerned, all religions are cults and enclaves of
> superstitious beliefs.

nobody really interested in what or how you feel.
subjectivity doesn't really interest anybody.

> Is it not justified that religious fanatics get splashed with the
> same paint they use to tarnish non-believers?

yes. exactly.
fanaticism is not allowed in Islam

al-Isra 17:36
"Do not follow things you do not understand .... " (al-Isra' 17:36)

al-Furqaan 25:69-73 .
"The penalty will be doubled for him on the Day of Judgment, and he
will abide therein despised forever, save he who repents and believes
and does righteous work; for such Allah will change their evil deeds
to good deeds. Allah is ever Forgiving, Merciful. And he who repents
and does good, verily, he has turned to Allah with true conversion.
And those who will not witness vanity (frivolous, foolish, ignorant,
futile and useless things, falsehood); and when they pass by vain
(frivolous, foolish, futile, ignorant, false) discourse, pass by with
dignity; and those who when they are reminded of the revelations of
their Lord, fall not deaf and blind thereat."

> > it is submission to Allah, this means that a Muslim also
> > submits, or ought to submit, consciously and deliberately -
> > he must be objective in thought, motive and action.
>
> > objective teaching can not be a cult.
>
> > > ..ie...the difference between the Brightside and
> > > Darkside spiritual forces...
>
> > Islam (genuine religion) is the Brightside
> > and corrupt teaching (made up teaching like Paul's and corrupted
> > Church doctrine) is the Darkside spiritual force.
>
> > > and what's in store for those who continue
> > > to believe this cult belief....it surely change your face's
> > > features...ie. changing one eye's look into squinted eye look...in
> > > some unfortunate muslim elders...-
>
> > yes, just like in HInduism, Chrsitianity, Buddhism, Judaism and
> > Atheism, there are also bad unfortunate leaders among Muslims.
> > don't yo know that too ?
>
> Bravo, you took such a long time to realize this!!!!!-

you are praising your own wrong observation.
that's idiotic.
umpteenth number of times I have said, being bad is not a monopoly of
non-Muslims like you.

Jokho Nyingkir

11/18/2010 5:21:00 AM

0

The Cynic <i.thecynic@gmail.com> wrote in news:5ddbc080-ccde-44d8-ad7d-
66541795613c@z19g2000yqb.googlegroups.com:

> What is your definition of "objective: and "subjective" vis-a-vis your
> religion?
>

this "smart" darion often warns people by posting ON THE INTERNET :

"do not trust anything on the internet"

(HA HA HA ...... he expects people to do something against
what he's suggesting)

so you will get that kind of moronic definition