How to implement Rails params from the ground up in Ruby?

Hi guys!
This time around I am going to show you how to implement Rails params completely from the ground up. As you probably already know, Rails has something called strong parameters. This is a security practice to prevent accidentally allowing users to update sensitive model attributes, for example “admin” flag in user model in the database. Someone could easily forge a request and modify this flag and what that means you probably understand. My goal this time is to implement params class so that I can do:

params.require(:person).permit(:name, :age)
class Params
  KeyNotFoundException = Class.new(StandardError)

  def initialize(values)
    @values = values
  end

  def require(key)
    raise KeyNotFoundException if @values[key].nil?
    @key = key
    self
  end

  def permit(*args)
    args.each_with_object({}) { |arg, hash| hash[arg] = @values[@key][arg] }
  end
end

values = {person: {name: 'Jedrek', age: 34}, anything_else: 'any_other_thing'}
params = Params.new(values)
puts params.require(:person).permit(:name, :age)

First, I create an error class which I throw in case the user passes a key that does not exist. Next, I implement #require method that accepts a key. It raised the error if a given key is invalid, otherwise hold the key in an instance variable and return self. Why is that? Because in order to be able to call permit I need to call it on the object, not on they. Self is the object itself in this case. #permit methods takes an array of attributes and I call #each_with_object on them and return a hash in which I add the keys and values which I pass to the new Params object. That’s it! Easy peasy šŸ™‚

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s