ActiveModel Series ActiveModel:API
What is ActiveModel::API?
ActiveModel::API
adds the ability for a ruby class to work with Action Pack and Action View right out of the box.
When including ActiveModel::API
we get some features of ActiveRecord:
- model name introspection
- conversions
- translations
- validations
For example
require 'active_model'
class Person
include ActiveModel::API
attr_accessor :name, :email
validates :name, :email, presence: true
endperson = Person.new(name: '', email: '')p person.valid?
#=> false
Above you can see that i am using the method validates to validate the attributes name and email.
Note: You should have rails gem installed in your system and you need to require active_model. Also you can see that to use the validates method i have included a active model’s module. include ActiveModel::API
So what is happening in the code above is, I created the object of class Person which has included a module ActiveModel::API.
Therefore, we can apply .valid? to Person’s object.
You may also note that:
ActiveModel::API gives us the ability to initialize an object with a hash of attributes, much like any Active Record object.
For example:
require 'active_model'
class Person
include ActiveModel::API
attr_accessor :name, :emailvalidates :name, :email, presence: trueend# initializing an object with a hash of arguments
person = Person.new(name: 'pratik', email: 'pratik@rubyonrails.com')
p person.name#=> 'pratik'
The documentation says:
Any class that includes
ActiveModel::API
can be used withform_with
,render
and any other Action View helper methods, just like Active Record objects.
Please refer to official documentation for more information
Thanks for giving it a read :)
Happy coding :)