Skip to content

Instantly share code, notes, and snippets.

@1gor
Forked from jgaskins/class.rb
Created February 16, 2019 13:28
Show Gist options
  • Save 1gor/d43b433666c342f70395cfcc074e3728 to your computer and use it in GitHub Desktop.
Save 1gor/d43b433666c342f70395cfcc074e3728 to your computer and use it in GitHub Desktop.
Class declarations in Ruby with lexical scopes vs closures
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
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