DEV Community

mixbo
mixbo

Posted on

1

Rails HashWithIndifferentAccess magical

Alt Text

In daily development the parameters passed to the action in the Controller when implementing business logic will be placed in the params object. generally we can access with

params[:token] #=> token_value
#or
params["token"] #=> token_value
Enter fullscreen mode Exit fullscreen mode

You will find that the value of key in params can be access by using Symbol or String.

Is it a bit magical?

In fact the principle is very simple params have the characteristics extend from HashWithIndifferentAccess

class HashWithIndifferentAccess < Hash
  #......
    def []=(key, value)
        regular_writer(convert_key(key), convert_value(value, for: :assignment))
    end

    # key point 
    def convert_key(key) 
       key.kind_of?(Symbol) ? key.to_s : key
    end

    def self.[](*args)
        new.merge!(Hash[*args])
    end
end
Enter fullscreen mode Exit fullscreen mode

Through the above source code analysis, it can be seen that for a HashWithIndifferentAccess object, when assigning it key is uniformly converted into String type (covert_key method).

When a value is to be taken, the key of the Symbol will be forced to be converted to String so that the user can use Symbol ** or **String to take the same value.

Hope it can hlep you :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more