Ruby on Rails offers a wide range of tools and modules to make application development more efficient and structured. One of these modules is ActiveSupport::Configurable
, which provides an elegant approach to handling configurations in our classes.
What is ActiveSupport::Configurable?
ActiveSupport::Configurable
is a concern in Rails that adds the ability to define configurations for objects. It allows defining default configurations and provides methods to access and modify these configurations easily.
Basic Usage
class Appointment
include ActiveSupport::Configurable
end
In this example, we have a class Appointment
, which thanks to the Concern Configurable
has the ability to be configured using options as follows:
Appointment.config.duration_in_minutes = 40
Appointment.config.recurrence = :weekly
This ensures that any instance created from this class will inherit and utilize that specific configuration:
irb(main)> Appointment.new.config.recurrence
=> :weekly
irb(main)> a = Appointment.first
irb(main)> a.config.recurrence = :monthly
irb(main)> a.config.recurrence # custom for this instance
=> :monthly
irb(main)> Appointment.new.config.recurrence
=> :weekly
Settings as Methods
If you want to access the settings as methods instead of through config
, we can declare the properties as accessors.
class Appointment
include ActiveSupport::Configurable
config_accessor :recurrence
config_accessor :duration_in_minutes
end
irb(main)> Appointment.recurrence = :weekly # class method
irb(main)> Appointment.new.recurrence # instance method
=> :weekly
Default Settings
class Appointment
include ActiveSupport::Configurable
config_accessor :recurrence { :weekly }
config_accessor :duration_in_minutes
end
In this case, recurrence
has a default value, while duration_in_minutes
does not. This provides flexibility by allowing some settings to have default values and others not.
Common Use Cases
- Gem Configuration: Many gems in Ruby on Rails use ActiveSupport::Configurable to allow developers to customize the behavior of the gem.
- Application Configuration: You can use ActiveSupport::Configurable to handle global configurations in your application.
- Inheritance: You can handle configurations through inheritance. For example, you could have default configurations in Appointment and have subclasses like MonthlyAppointment, WeeklyAppointment that override
recurrence
.
Conclusion
ActiveSupport::Configurable is a powerful tool for handling configurations in Ruby on Rails. Its flexibility and simplicity make it a solid choice for situations where you need to configure classes dynamically and efficiently.