module Line::Message::Builder::Base::ClassMethods
The ClassMethods module is automatically extended by any class that inherits from Base. It provides class-level methods for defining DSL options and configurations.
Public Instance Methods
Source
# File lib/line/message/builder/base.rb, line 59 def option(name, default: nil, validator: nil) options << name define_method name do |*args| if args.empty? instance_variable_get("@#{name}") || default else validator&.valid!(args.first) instance_variable_set("@#{name}", args.first) end end end
Defines a new option for the builder class.
This method dynamically creates an instance method on the builder class with the given name. When this instance method is called:
-
Without arguments, it returns the current value of the option, or the default value if not set.
-
With an argument, it sets the value of the option. If a validator is provided, the value is validated before being set.
- name
-
The name of the option to define. This will also be the name of the generated instance method.
- default
-
The default value for the option if not explicitly set.
- validator
-
An optional validator object that must respond to
valid!method. If the value is invalid, the validator should raise an error.
Example
class MyBuilder < Base option :color, default: "red" option :size, validator: SizeValidator.new end builder = MyBuilder.new puts builder.color # => "red" builder.color "blue" puts builder.color # => "blue" builder.size "large" # Assuming SizeValidator allows "large"