-
-
Save 1gor/d43b433666c342f70395cfcc074e3728 to your computer and use it in GitHub Desktop.
Class declarations in Ruby with lexical scopes vs closures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'primalize' | |
# Because TicketOwnerSerializer is a constant, it is available | |
# anywhere in the app. We could nest it inside of TicketSerializer, | |
# but it has to exist before TicketSerializer's attributes declaration, | |
# so it would push that down. | |
class TicketOwnerSerializer < Primalize::Single | |
attributes( | |
id: string, | |
name: string, | |
email: string, | |
) | |
end | |
class TicketSerializer < Primalize::Single | |
attributes( | |
id: string, | |
title: string, | |
description: string, | |
owner: primalize(TicketOwnerSerializer) { |owner| | |
owner || DEFAULT_OWNER | |
}, | |
) | |
# This is available anywhere in the app as TicketSerializer::DEFAULT_OWNER | |
# We could make it a private_constant | |
DEFAULT_OWNER = OpenStruct.new( | |
id: '', | |
name: 'Unassigned', | |
email: '[email protected]', | |
) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'primalize' | |
# These local variables can't be used outside of this file, | |
# making them actually private. | |
ticket_owner_serializer = Class.new(Primalize::Single) do | |
attributes( | |
id: string, | |
name: string, | |
email: string, | |
) | |
end | |
default_owner = OpenStruct.new( | |
id: '', | |
name: 'Unassigned', | |
email: '[email protected]', | |
) | |
TicketSerializer = Class.new(Primalize::Single) do | |
attributes( | |
id: string, | |
title: string, | |
description: string, | |
owner: primalize(ticket_owner_serializer) { |owner| | |
owner || default_owner | |
}, | |
) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment