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
more...

Overview

This file includes public constants to prevent circular dependencies.

Defined Under Namespace

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

Constant Summary collapse

Serializer =
Resource
REMOVE_KEY =

A constant to remove key from serialized JSON

Object.new.freeze

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.backendObject

Returns the value of attribute backend.

[View on GitHub]

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

def backend
  @backend
end

.encoderObject

Returns the value of attribute encoder.

[View on GitHub]

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

def encoder
  @encoder
end

.inflectorObject

Getter for inflector, a module responsible for inflecting strings

[View on GitHub]

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

def inflector
  @inflector
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. When object is a Struct, it’s Enumerable but not a collection

Returns:

  • (Boolean)
[View source] [View on GitHub]

85
86
87
# File 'lib/alba.rb', line 85

def collection?(object)
  object.is_a?(Enumerable) && !object.is_a?(Struct)
end

.disable_inference!Object

Deprecated.

Use inflector= instead

Disable inference for key and resource name

[View source] [View on GitHub]

104
105
106
107
108
# File 'lib/alba.rb', line 104

def disable_inference!
  Alba::Deprecation.warn('Alba.disable_inference! is deprecated. Use `Alba.inflector = nil` instead.')
  @inferring = false
  @inflector = nil
end

.enable_inference!(with:) ⇒ Object

Deprecated.

Use inflector= instead

Enable inference for key and resource name

Parameters:

  • with (Symbol, Class, Module)

    inflector When it’s a Symbol, it sets inflector with given name When it’s a Class or a Module, it sets given object to inflector

[View source] [View on GitHub]

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

def enable_inference!(with:)
  Alba::Deprecation.warn('Alba.enable_inference! is deprecated. Use `Alba.inflector=` instead.')
  @inflector = inflector_from(with)
  @inferring = true
end

.find_type(name) ⇒ Alba::Type

Find type by name

Returns:

[View source] [View on GitHub]

208
209
210
211
212
# File 'lib/alba.rb', line 208

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

Returns:

  • (String)

    serialized JSON string

Raises:

  • (ArgumentError)

    if both object and block are not given

[View source] [View on GitHub]

70
71
72
73
74
75
76
77
78
79
# File 'lib/alba.rb', line 70

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, &block)
  else
    resource = resource_with(object, &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

Returns:

Raises:

[View source] [View on GitHub]

139
140
141
142
143
144
145
146
147
148
# File 'lib/alba.rb', line 139

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

Deprecated.

Use inflector instead

Returns whether inference is enabled or not.

Returns:

  • (Boolean)

    whether inference is enabled or not

[View source] [View on GitHub]

112
113
114
115
# File 'lib/alba.rb', line 112

def inferring
  Alba::Deprecation.warn('Alba.inferring is deprecated. Use `Alba.inflector` instead.')
  @inferring
end

.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

See Also:

[View source] [View on GitHub]

201
202
203
# File 'lib/alba.rb', line 201

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)

Returns:

  • (Symbol, String, nil)
[View source] [View on GitHub]

167
168
169
170
171
172
# File 'lib/alba.rb', line 167

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

[View source] [View on GitHub]

216
217
218
219
220
221
222
223
224
# File 'lib/alba.rb', line 216

def reset!
  @encoder = default_encoder
  @symbolize_keys = false
  @_on_error = :raise
  @_on_nil = nil
  @types = {}
  reset_transform_keys
  register_default_types
end

.resource_class(&block) ⇒ Class<Alba::Resource>

Returns resource class.

Parameters:

  • block (Block)

    resource body

Returns:

[View source] [View on GitHub]

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

def resource_class(&block)
  klass = Class.new
  klass.include(Alba::Resource)
  klass.class_eval(&block) if block
  klass
end

.resource_with(object, with: :inference, &block) ⇒ Alba::Resource

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

Parameters:

  • object (Object)

    the object whose class name is used for inferring resource class

  • 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

Returns:

  • (Alba::Resource)

    resource class with ‘object` as its target object

Raises:

  • (ArgumentError)

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

[View source] [View on GitHub]

238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/alba.rb', line 238

def resource_with(object, with: :inference, &block) # rubocop:disable Metrics/MethodLength
  klass = if block
            resource_class(&block)
          else
            case with
            when :inference then infer_resource_class(object.class.name)
            when Class then with
            when Proc then with.call(object)
            else raise ArgumentError, '`with` argument must be either :inference, Proc or Class'
            end
          end

  klass.new(object)
end

.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

Returns:

  • (String)

    serialized JSON string

Raises:

  • (ArgumentError)

    if both object and block are not given

[View source] [View on GitHub]

50
51
52
53
54
55
56
57
58
59
60
# File 'lib/alba.rb', line 50

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, &block)
    Alba.encoder.call(h)
  else
    resource = resource_with(object, &block)
    resource.serialize(root_key: root_key)
  end
end

.stringify_keys!Object

Configure Alba to stringify (not symbolize) keys

[View source] [View on GitHub]

157
158
159
160
# File 'lib/alba.rb', line 157

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

.symbolize_keys!Object

Configure Alba to symbolize keys

[View source] [View on GitHub]

151
152
153
154
# File 'lib/alba.rb', line 151

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`

Returns:

  • (String)

Raises:

[View source] [View on GitHub]

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/alba.rb', line 179

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