Skip to content

Instantly share code, notes, and snippets.

@selvagsz
Last active February 18, 2019 11:30
Show Gist options
  • Save selvagsz/9dc0de1c5a3b21e4e4aa242df010d9a4 to your computer and use it in GitHub Desktop.
Save selvagsz/9dc0de1c5a3b21e4e4aa242df010d9a4 to your computer and use it in GitHub Desktop.
class Policy
class << self
def rename_attributes(&block)
@root ||= {}
@block = block
end
def mapped_attributes
instance_eval(&@block)
@root
end
def rename(from:, to:, &attribues_block)
children = instance_eval(&attribues_block) if block_given?
@root[from] = {
to: to,
children: children,
}
@root
end
def delegates_renaming_to(policy_klass)
policy_klass.mapped_attributes
end
end
end
#########
## DSL ##
#########
class StockGroupPolicy < Policy
rename_attributes do
rename from: :batch, to: :stock_group_attributes
rename from: :batch_id, to: :stock_group_id
end
end
class StockAdjustmentLineItemPolicy < Policy
rename_attributes do
rename from: :stock_trails, to: :stock_trails_attrs do
delegates_renaming_to StockGroupPolicy
end
end
end
class StockAdjustmentPolicy < Policy
rename_attributes do
rename from: :stock_adjustment_line_items, to: :stock_adjustment_line_items_attrs do
delegates_renaming_to StockAdjustmentLineItemPolicy
end
end
end
## `mapped_attributes` builds the schema which will be used by controller#some_before_action to modify the action parameters
StockAdjustmentPolicy.mapped_attributes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment