Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3609

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T04:19:08+00:00 2024-11-26T04:19:08+00:00

Automatically cast params with the Rails Attributes API

  • 61k

A common practice in Rails apps is to extract logic into plain-old Ruby objects (POROs). But often you are passing data to these objects directly from controller params and the data comes in as strings.

class SalesReport   attr_accessor :start_date, :end_date, :min_items    def initialize(params = {})     @start_date = params[:start_date]     @end_date = params[:end_date]     @min_items = params[:min_items]   end    def run!     # Do some cool stuff   end end  report = SalesReport.new(start_date: "2020-01-01", end_date: "2020-03-01", min_items: "10")  # But the data is just stored as strings :( report.start_date # => "2020-01-01" report.min_items # => "10" 
Enter fullscreen mode Exit fullscreen mode

You probably want start_date to be a date and min_items to be an integer. You could add your own basic type casting to the constructor.

class SalesReport   attr_accessor :start_date, :end_date, :min_items    def initialize(params)     @start_date = Date.parse(params[:start_date])     @end_date = Date.parse(params[:end_date])     @min_items = params[:min_items].to_i   end    def run!     # Do some cool stuff   end end 
Enter fullscreen mode Exit fullscreen mode

But even better, you could take advantage of the Attributes API to handle this casting automatically.

Usage

As of Rails 6.1, this module is technically a private API. Use at your own risk!

The Rails Attributes API is used under-the-hood to type cast attributes for ActiveRecord models. When you query for a model that has a datetime column in the database and the Ruby object that gets pulled out has a DateTime field – that’s the Attributes API at work.

We can spruce up our report model by mixing in the ActiveModel::Model and ActiveModel::Attributes modules.

class SalesReport   include ActiveModel::Model   include ActiveModel::Attributes    attribute :start_date, :date   attribute :end_date, :date   attribute :min_items, :integer    def run!     # Do some cool stuff   end end  report = SalesReport.new(start_date: "2020-01-01", end_date: "2020-03-01", min_items: "10")  # Now the attributes are native types!  report.start_date # => Wed, 01 Jan 2020 report.min_items # => 10 
Enter fullscreen mode Exit fullscreen mode

This pattern is great for reducing boilerplate code in form objects, report objects, or any other Model-ish Ruby class in your Rails apps. Let the framework do the type casting for you, instead of trying to reimplement it yourself!

Options

The Attribute API will automatically handle type casting for most primitives. All of the basics are covered.

attribute :start_date, :date attribute :max_size, :integer attribute :enabled, :boolean attribute :score, :float 
Enter fullscreen mode Exit fullscreen mode

You can find the full list of out-of-the-box types here: activemodel/lib/active_model/type.

The coolest part is that the types are very robust in what kind of input they accept. For example, the boolean Attribute type works with any of these values for false:

FALSE_VALUES = [   false, 0,   "0", :"0",   "f", :f,   "F", :F,   "false", :false,   "FALSE", :FALSE,   "off", :off,   "OFF", :OFF, ] 
Enter fullscreen mode Exit fullscreen mode

You can also register your own custom types that implement cast and serialize:

ActiveRecord::Type.register(:zip_code, ZipCodeType)  class ZipCodeType < ActiveRecord::Type::Value   def cast(value)     ZipCode.new(value) # cast to your own ZipCode class for special handling   end    def serialize(value)     value.to_s   end end 
Enter fullscreen mode Exit fullscreen mode

Additionally, you can set a default value for with the Attributes API:

attribute :start_date, :date, default: 30.days.ago attribute :max_size, :integer, default: 15 attribute :enabled, :boolean, default: true attribute :score, :float, default: 9.75 
Enter fullscreen mode Exit fullscreen mode

Additional Resources

Rails API Docs: Attributes API

Blog post: Rails’ hidden type system


railsrubywebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.