lost9123193
lost9123193

Reputation: 11030

Simplify Rails Method and nested variable

I have 2 methods as seen below:

def post(type, params=nil)
    if params
    @animalCategory.post(type, params:params[:params], header:{...}) 
    else 
      @animalCategory.post(type, header:{...}) 
    end
  end

  def put(route, params=nil)
    if params
      @animalCategory.put(type, params:params[:params], header:{...})  
    else
      @animalCategory.put(type, header:{...})  
    end
  end

It gets called like this:

 animal_category.put '/cat', params: data

I have a wrapper for two functions above. They basically do the same thing except one calls a post and the other calls a put. I'm wondering if there's a way to merge/simplify it. Also, is there a suggested way to simplify the extraction of params:params[:params]?

Upvotes: 1

Views: 42

Answers (1)

max pleaner
max pleaner

Reputation: 26758

def put_or_post(http_method, type, params=nil)
  if params
    @animalCategory.send(http_method, type, params:params[:params], header:{...}) 
  else 
    @animalCategory.send(http_method, type, header:{...}) 
  end
end

Use Object#send to call methods from variables

You can then refactor the other methods to call this one:

def put(*args)
  put_or_post :put, *args
end

def post(*args)
  put_or_post :post, *args
end

and leave your original call signature (animal_category.put) the same

Upvotes: 2

Related Questions