On 27.09.2009 15:07, Jp Hastings-spital wrote:
> Hi all,
> 
> I have a module containing two classes the first is 'item' the second is
> 'search'. Lets use twitter as an example:
> module MyTwitter
>   class Item
>     attribute_reader :id, :tweet
>     def initialize(text)
>       @tweet = text
>       # Post to twitter
>       @id = id_from_post_operation
>     end
>   end
> 
>   class Search
>     def self.do(q)
>       # perform search
>       out = []
>       results.each do |hit|
>         # This is the problem point:
>         out << Item.new_from_data(hit.id,hit.text)
>       end
>       return out
>     end
>   end
> end
> 
> When I create a new Item object I have code that creates a new tweet
> however I'd like my Search to return an array of Item objects, but if I
> use the standard MyTwitter::Item.new I'll be posting a new item,
> not simply creating an object with the id I have from my search.
> 
> Is there a way to create an object with a given attribute without
> calling .new?
> 
> I hope I've explained myself well enough! Thanks,
> JP

You could do:

class Item
   def self.new_from_data(id, text)
     it = allocate
     it.id = id
     it.text = text
     it
   end
end

Or change your initialize logic to handle both cases.

Cheers

	robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/