Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a method trailing with a keyword

I have a situation where i need to call something like this :

class Office
   attr_accessor :workers, :id

   def initialize
      @workers = []
   end

   def workers<<(worker)
      type = worker.type
      resp = Organiation::Worker.post("/office/#{@id}/workers.json", :worker => {:type => type})
   end
end

this is where i need to call

office = Office.new()

new_worker = Worker.new()

office.workers << new_worker

how should i modify the above workers method in order to implement above code.

like image 289
Manish Das Avatar asked Jun 03 '11 10:06

Manish Das


2 Answers

New answer for this (based on updated question):

class WorkersClient
  attr_accessor :office_id

  def <<(worker)
    type = worker.type
    resp = Organiation::Worker.post("/office/#{@office_id}/workers.json", :worker => {:type => type})
  end
end

class Office
  attr_accessor :workers, :id

  def initialize
    @workers = WorkersClient.new
    @workers.office_id = @id
  end
end

I'm assuming that the Worker class is defined somewhere, something like:

def Worker
  attr_accessor :type
  ...
end

The WorkersClient class is just a proxy to handle the collection (like ActiveRecord 3 does with associations). You can develop it further to store a local cache of workers, and so on.

I would recommend looking at how Rails' ActiveResource is implemented, as it does something VERY similar.

like image 101
Jits Avatar answered Oct 16 '22 20:10

Jits


try this office.build_worker

like image 3
Sadiksha Gautam Avatar answered Oct 16 '22 19:10

Sadiksha Gautam