Module: Alba

Defined in:
lib/alba.rb,
lib/alba/type.rb,
lib/alba/errors.rb,
lib/alba/layout.rb,
lib/alba/railtie.rb,
lib/alba/resource.rb,
lib/alba/constants.rb,
lib/alba/association.rb,
lib/alba/deprecation.rb,
lib/alba/typed_attribute.rb,
lib/alba/nested_attribute.rb,
lib/alba/default_inflector.rb,
lib/alba/conditional_attribute.rb,
sig/alba.rbs,
sig/alba/type.rbs,
sig/alba/errors.rbs,
sig/alba/layout.rbs,
sig/alba/railtie.rbs,
sig/alba/version.rbs,
sig/alba/resource.rbs,
sig/alba/constants.rbs,
sig/alba/association.rbs,
sig/alba/deprecation.rbs,
sig/alba/typed_attribute.rbs,
sig/alba/nested_attribute.rbs,
sig/alba/default_inflector.rbs,
sig/alba/conditional_attribute.rbs

Overview

This file includes public constants to prevent circular dependencies.

Defined Under Namespace

Modules: DefaultInflector, Deprecation, Resource, _Inflector Classes: Association, ConditionalAttribute, Error, Layout, NestedAttribute, Railtie, Type, TypedAttribute, UnsupportedBackend, UnsupportedType

Constant Summary collapse

Serializer =

Returns:

Resource
REMOVE_KEY =

A constant to remove key from serialized JSON

Returns:

  • (Object)
Object.new.freeze
VERSION =

Current version of Alba

Returns:

  • (String)

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.backendbackend_type

Returns the value of attribute backend.

Returns:

  • (backend_type)


14
15
16
# File 'lib/alba.rb', line 14

def backend
  @backend
end

.default_superclass=(value) ⇒ Object (writeonly)

Set the default superclass for resource classes created with resource_class

Examples:

Alba.default_superclass = '::MyApp::BaseResource'

Parameters:

  • value (Class, String, Symbol)

    the default superclass



27
28
29
# File 'lib/alba.rb', line 27

def default_superclass=(value)
  @default_superclass = value
end

.encoderObject

Returns the value of attribute encoder.

Returns:

  • (Object)


14
15
16
# File 'lib/alba.rb', line 14

def encoder
  @encoder
end

.inflectorinflector_type

Getter for inflector, a module responsible for inflecting strings

Returns:

  • (inflector_type)


17
18
19
# File 'lib/alba.rb', line 17

def inflector
  @inflector
end

.non_collection_typesArray<Class> (readonly)

Returns classes that include Enumerable but should not be treated as collections.

Returns:

  • (Array<Class>)

    classes that include Enumerable but should not be treated as collections



20
21
22
# File 'lib/alba.rb', line 20

def non_collection_types
  @non_collection_types
end

Class Method Details

.collection?(object) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Detect if object is a collection or not. Types in non_collection_types (default: Struct, Range, Hash) are considered non-collection even if they include Enumerable.

Parameters:

  • object (Object)

Returns:

  • (Boolean)


96
97
98
# File 'lib/alba.rb', line 96

def collection?(object)
  object.is_a?(Enumerable) && @non_collection_types.none? { |type| object.is_a?(type) }
end

.disable_inference!Object

Returns:

  • (Object)


47
# File 'sig/alba.rbs', line 47

def self.disable_inference!: () -> untyped

.enable_inference!Object

Parameters:

  • with: (Object)

Returns:

  • (Object)


46
# File 'sig/alba.rbs', line 46

def self.enable_inference!: (with: untyped) -> untyped

.find_type(name) ⇒ Alba::Type

Find type by name

Parameters:

Returns:



195
196
197
198
199
# File 'lib/alba.rb', line 195

def find_type(name)
  @types.fetch(name) do
    raise(Alba::UnsupportedType, "Unknown type: #{name}")
  end
end

.hashify(object = nil, with: :inference, root_key: nil, &block) ⇒ String

Hashify the object with inline definitions

Parameters:

  • object (Object) (defaults to: nil)

    the object to be serialized

  • with (:inference, Proc, Class<Alba::Resource>) (defaults to: :inference)

    determines how to get resource class for each object

  • root_key (Symbol, nil, true) (defaults to: nil)
  • block (Block)

    resource block

  • with: (Object) (defaults to: :inference)
  • root_key: (root_key_type) (defaults to: nil)

Returns:

  • (String)

    serialized JSON string

Raises:

  • (ArgumentError)

    if both object and block are not given



80
81
82
83
84
85
86
87
88
89
# File 'lib/alba.rb', line 80

def hashify(object = nil, with: :inference, root_key: nil, &block)
  raise ArgumentError, 'Either object or block must be given' if object.nil? && block.nil?

  if collection?(object)
    hashify_collection(object, with, root_key, &block)
  else
    resource = resource_for(object, with: with, &block)
    resource.as_json(root_key: root_key)
  end
end

.infer_resource_class(name, nesting: nil) ⇒ Class<Alba::Resource>

Returns resource class.

Parameters:

  • name (String)

    a String Alba infers resource name with

  • nesting (String, nil) (defaults to: nil)

    namespace Alba tries to find resource class in

  • (String, Symbol)
  • nesting: (String, nil) (defaults to: nil)

Returns:

Raises:



126
127
128
129
130
131
132
133
134
135
# File 'lib/alba.rb', line 126

def infer_resource_class(name, nesting: nil)
  raise Alba::Error, 'Inference is disabled so Alba cannot infer resource name. Set inflector before use.' unless Alba.inflector

  const_parent = nesting.nil? ? Object : Object.const_get(nesting)
  begin
    const_parent.const_get("#{inflector.classify(name)}Resource")
  rescue NameError # Retry for serializer
    const_parent.const_get("#{inflector.classify(name)}Serializer")
  end
end

.inferringBoolean

Returns:

  • (Boolean)


48
# File 'sig/alba.rbs', line 48

def self.inferring: () -> bool

.register_type(name, check: false, converter: nil, auto_convert: false) ⇒ void

This method returns an undefined value.

Register types, used for both builtin and custom types

Parameters:

  • (Symbol, Class)
  • check: (Object) (defaults to: false)
  • converter: (Object) (defaults to: nil)
  • auto_convert: (Boolean) (defaults to: false)

See Also:



188
189
190
# File 'lib/alba.rb', line 188

def register_type(name, check: false, converter: nil, auto_convert: false)
  @types[name] = Type.new(name, check: check, converter: converter, auto_convert: auto_convert)
end

.regularize_key(key) ⇒ Symbol, ...

Regularize key to be either Symbol or String depending on @symbolize_keys Returns nil if key is nil

Parameters:

  • key (String, Symbol, nil)
  • (root_key_type)

Returns:

  • (Symbol, String, nil)


154
155
156
157
158
159
# File 'lib/alba.rb', line 154

def regularize_key(key)
  return if key.nil?
  return key.to_sym if @symbolize_keys

  key.is_a?(Symbol) ? key.name : key.to_s
end

.reset!Object

Reset config variables Useful for test cleanup

Returns:

  • (Object)


203
204
205
206
207
208
209
210
211
212
213
# File 'lib/alba.rb', line 203

def reset!
  @encoder = default_encoder
  @symbolize_keys = false
  @_on_error = :raise
  @_on_nil = nil
  @types = {}
  @non_collection_types = [Struct, Range, Hash]
  @default_superclass = ::Object
  reset_transform_keys
  register_default_types
end

.resource_class(helper: nil, key_transformation: :none, &block) ⇒ Class<Alba::Resource>

Returns resource class.

Parameters:

  • helper (Module) (defaults to: nil)

    helper module to include

  • key_transformation (Symbol) (defaults to: :none)

    key transformation type

  • block (Block)

    resource body

  • helper: (Module, nil) (defaults to: nil)
  • key_transformation: (transform_type) (defaults to: :none)

Returns:



114
115
116
117
118
119
120
121
# File 'lib/alba.rb', line 114

def resource_class(helper: nil, key_transformation: :none, &block)
  klass = Class.new(resolved_default_superclass)
  klass.include(Alba::Resource)
  klass.helper(helper) if helper
  klass.transform_keys(key_transformation)
  klass.class_eval(&block) if block
  klass
end

.resource_for(arg0, params:, with:) ⇒ Object .resource_for(arg0, params:, with:) ⇒ Object

Get a resource object from arguments If block is given, it creates a resource class with the block Otherwise, it behaves depending on with argument

Overloads:

  • .resource_for(arg0, params:, with:) ⇒ Object

    Parameters:

    • arg0 (Object)
    • params: (generic_hash)
    • with: (Object)

    Returns:

    • (Object)
  • .resource_for(arg0, params:, with:) ⇒ Object

    Parameters:

    • arg0 (Object)
    • params: (generic_hash)
    • with: (Object)

    Returns:

    • (Object)

Parameters:

  • object (Object)

    the object whose class name is used for inferring resource class

  • params (Hash) (defaults to: {})

    user-given Hash for arbitrary data

  • with (:inference, Proc, Class<Alba::Resource>) (defaults to: :inference)

    determines how to get resource class for object When it's :inference, it infers resource class from object's class name When it's a Proc, it calls the Proc with object as an argument When it's a Class, it uses the Class as a resource class Otherwise, it raises an ArgumentError

Yields:

Yield Returns:

  • (void)

Returns:

  • (Alba::Resource)

    resource class with object as its target object

Raises:

  • (ArgumentError)

    if with argument is not one of :inference, Proc or Class



228
229
230
# File 'lib/alba.rb', line 228

def resource_for(object, params: {}, with: :inference, &block)
  _resource_for(object, params: params, with: with, &block)
end

.resource_withvoid

This method returns an undefined value.

Parameters:

  • (Object)
  • with: (Object)


59
# File 'sig/alba.rbs', line 59

def self.resource_with: (untyped, ?with: untyped) ?{ () -> void } -> untyped

.serialize(object = nil, with: :inference, root_key: nil, &block) ⇒ String

Serialize the object with inline definitions

Parameters:

  • object (Object) (defaults to: nil)

    the object to be serialized

  • with (:inference, Proc, Class<Alba::Resource>) (defaults to: :inference)

    determines how to get resource class for each object

  • root_key (Symbol, nil, true) (defaults to: nil)
  • block (Block)

    resource block

  • with: (Object) (defaults to: :inference)
  • root_key: (root_key_type) (defaults to: nil)

Returns:

  • (String)

    serialized JSON string

Raises:

  • (ArgumentError)

    if both object and block are not given



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/alba.rb', line 60

def serialize(object = nil, with: :inference, root_key: nil, &block)
  raise ArgumentError, 'Either object or block must be given' if object.nil? && block.nil?

  if collection?(object)
    h = hashify_collection(object, with, root_key, &block)
    Alba.encoder.call(h)
  else
    resource = resource_for(object, with: with, &block)
    resource.serialize(root_key: root_key)
  end
end

.stringify_keys!Object

Configure Alba to stringify (not symbolize) keys

Returns:

  • (Object)


144
145
146
147
# File 'lib/alba.rb', line 144

def stringify_keys!
  reset_transform_keys if @symbolize_keys
  @symbolize_keys = false
end

.symbolize_keys!Object

Configure Alba to symbolize keys

Returns:

  • (Object)


138
139
140
141
# File 'lib/alba.rb', line 138

def symbolize_keys!
  reset_transform_keys unless @symbolize_keys
  @symbolize_keys = true
end

.transform_key(key, transform_type:) ⇒ String

Transform a key with given transform_type

Parameters:

  • key (String)

    a target key

  • transform_type (Symbol)

    a transform type, either one of camel, lower_camel, dash or snake

  • (String, Symbol)
  • transform_type: (transform_type)

Returns:

  • (String)

Raises:



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/alba.rb', line 166

def transform_key(key, transform_type:) # rubocop:disable Metrics/MethodLength
  raise Alba::Error, 'Inflector is nil. You must set inflector before transforming keys.' unless inflector

  @_transformed_keys[transform_type][key] ||= begin
    key = key.to_s

    k = case transform_type
        when :camel then inflector.camelize(key)
        when :lower_camel then inflector.camelize_lower(key)
        when :dash then inflector.dasherize(key)
        when :snake then inflector.underscore(key)
        else raise Alba::Error, "Unknown transform type: #{transform_type}"
        end

    regularize_key(k)
  end
end