Module: Alba::Resource::ClassMethods

Included in:
Alba::Resource
Defined in:
lib/alba/resource.rb

Overview

Class methods

Instance Method Summary collapse

Instance Method Details

#association(name, condition = nil, resource: nil, serializer: nil, source: nil, key: nil, with_traits: nil, params: EMPTY_HASH, **options, &block) ⇒ void Also known as: one, many, has_one, has_many

This method returns an undefined value.

Set association

Parameters:

  • name (String, Symbol)

    name of the association, used as key when ‘key` param doesn’t exist

  • condition (Proc, nil) (defaults to: nil)

    a Proc to modify the association

  • resource (Class<Alba::Resource>, String, Proc, nil) (defaults to: nil)

    representing resource for this association

  • serializer (Class<Alba::Resource>, String, Proc, nil) (defaults to: nil)

    alias for ‘resource`

  • source (Proc, nil) (defaults to: nil)

    a Proc to customize the association source

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

    used as key when given

  • with_traits (Symbol, Array<Symbol>, nil) (defaults to: nil)

    specified traits

  • params (Hash) (defaults to: EMPTY_HASH)

    params override for the association

  • options (Hash<Symbol, Proc>)
  • block (Block)

Options Hash (**options):

  • if (Proc, Symbol, nil)

    a condition to decide if this association should be serialized When it’s Proc, it’s called to check condition When it’s Symbol, it’s treated as a method name on the Resource and the method is called

See Also:



453
454
455
456
457
458
459
460
461
462
# File 'lib/alba/resource.rb', line 453

def association(name, condition = nil, resource: nil, serializer: nil, source: nil, key: nil, with_traits: nil, params: EMPTY_HASH, **options, &block)
  resource ||= serializer
  transformation = @_key_transformation_cascade ? @_transform_type : :none
  assoc = Association.new(
    name: name, condition: condition, resource: resource, source: source, with_traits: with_traits,
    params: params, nesting: nesting, key_transformation: transformation, helper: @_helper,
    &block
  )
  @_attributes[key&.to_sym || name.to_sym] = options[:if] ? ConditionalAttribute.new(body: assoc, condition: options[:if]) : assoc
end

#attribute(name = nil, if: nil, **name_with_type, &block) ⇒ void

This method returns an undefined value.

Set an attribute with the given block

Parameters:

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

    key name

  • if (Proc) (defaults to: nil)

    condition to decide if it should serialize these attributes

  • block (Block)

    the block called during serialization

Raises:

  • (ArgumentError)

    if block is absent



423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/alba/resource.rb', line 423

def attribute(name = nil, if: nil, **name_with_type, &block)
  if_value = binding.local_variable_get(:if)
  raise ArgumentError, 'No block given in attribute method' unless block
  raise ArgumentError, 'You must specify either name or name with type' if name.nil? && name_with_type.empty?

  if name.nil?
    assign_attributes_with_types(name_with_type, if_value, &block)
  else # Symbol
    attr = if_value ? ConditionalAttribute.new(body: block, condition: if_value) : block
    @_attributes[name.to_sym] = attr
  end
end

#attributes(*attrs, if: nil, **attrs_with_types) ⇒ void

This method returns an undefined value.

Set multiple attributes at once

Parameters:

  • attrs (Array<String, Symbol>)
  • if (Proc) (defaults to: nil)

    condition to decide if it should serialize these attributes

  • attrs_with_types (Hash{Symbol, String => Array<Symbol, Proc>, Symbol})

    attributes with name in its key and type and optional type converter in its value



390
391
392
393
394
# File 'lib/alba/resource.rb', line 390

def attributes(*attrs, if: nil, **attrs_with_types)
  if_value = binding.local_variable_get(:if)
  assign_attributes(attrs, if_value)
  assign_attributes_with_types(attrs_with_types, if_value)
end

#collection_key(key) ⇒ void

This method returns an undefined value.

Sets key for collection serialization

Parameters:

  • key (String, Symbol)


592
593
594
# File 'lib/alba/resource.rb', line 592

def collection_key(key)
  @_collection_key = key.to_sym
end

#helper(mod = @_helper || Module.new, &block) ⇒ void

This method returns an undefined value.

Define helper methods

Parameters:

  • mod (Module) (defaults to: @_helper || Module.new)

    a module to extend



632
633
634
635
636
637
# File 'lib/alba/resource.rb', line 632

def helper(mod = @_helper || Module.new, &block)
  mod.module_eval(&block) if block
  extend mod

  @_helper = mod
end

#inherited(subclass) ⇒ Object

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.



376
377
378
379
# File 'lib/alba/resource.rb', line 376

def inherited(subclass)
  super
  INTERNAL_VARIABLES.each_key { |name| subclass.instance_variable_set(:"@#{name}", instance_variable_get(:"@#{name}").clone) }
end

#layout(file: nil, inline: nil) ⇒ void

This method returns an undefined value.

Set layout

Parameters:

  • file (String) (defaults to: nil)

    name of the layout file

  • inline (Proc) (defaults to: nil)

    a proc returning JSON string or a Hash representing JSON



546
547
548
# File 'lib/alba/resource.rb', line 546

def layout(file: nil, inline: nil)
  @_layout = Layout.new(file: file, inline: inline)
end

#meta(key = :meta, &block) ⇒ void

This method returns an undefined value.

Set metadata



537
538
539
# File 'lib/alba/resource.rb', line 537

def meta(key = :meta, &block)
  @_meta = [key, block]
end

#method_added(method_name) ⇒ Object

This ‘method_added` is used for defining “resource methods”



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/alba/resource.rb', line 355

def method_added(method_name) # rubocop:disable Metrics/MethodLength
  case method_name
  when :collection_converter, :converter
    warn "Defining ##{method_name} methods is deprecated", category: :deprecated, uplevel: 1
    alias_method :serializable_hash_for_collection, :deprecated_serializable_hash_for_collection
    private(:serializable_hash_for_collection)
    alias_method :serializable_hash, :deprecated_serializable_hash
    alias_method :to_h, :deprecated_serializable_hash
  when :attributes
    warn 'Overriding `attributes` is deprecated, use `select` instead.', category: :deprecated, uplevel: 1
  when :select
    @_select_arity = instance_method(:select).arity
  when :_setup # noop
  else
    _resource_methods << method_name.to_sym
  end

  super
end

#nested_attribute(name, **options, &block) ⇒ void Also known as: nested

This method returns an undefined value.

Set a nested attribute with the given block

Parameters:

  • name (String, Symbol)

    key name

  • options (Hash<Symbol, Proc>)
  • block (Block)

    the block called during serialization

Options Hash (**options):

  • if (Proc)

    a condition to decide if this attribute should be serialized

Raises:

  • (ArgumentError)

    if block is absent



485
486
487
488
489
490
491
# File 'lib/alba/resource.rb', line 485

def nested_attribute(name, **options, &block)
  raise ArgumentError, 'No block given in attribute method' unless block

  key_transformation = @_key_transformation_cascade ? @_transform_type : :none
  attribute = NestedAttribute.new(key_transformation: key_transformation, &block)
  @_attributes[name.to_sym] = options[:if] ? ConditionalAttribute.new(body: attribute, condition: options[:if]) : attribute
end

#on_error(handler = nil, &block) ⇒ void

This method returns an undefined value.

Set error handler If this is set it’s used as a error handler overriding global one

Parameters:

  • handler (Symbol) (defaults to: nil)

    ‘:raise`, `:ignore` or `:nullify`

  • block (Block)

Raises:

  • (ArgumentError)


602
603
604
605
606
607
# File 'lib/alba/resource.rb', line 602

def on_error(handler = nil, &block)
  raise ArgumentError, 'You cannot specify error handler with both Symbol and block' if handler && block
  raise ArgumentError, 'You must specify error handler with either Symbol or block' unless handler || block

  @_on_error = block || validated_error_handler(handler)
end

#on_nil(&block) ⇒ void

This method returns an undefined value.

Set nil handler

Parameters:

  • block (Block)


624
625
626
# File 'lib/alba/resource.rb', line 624

def on_nil(&block)
  @_on_nil = block
end

#prefer_object_method!void

This method returns an undefined value.

DSL for alias, purely for readability



647
648
649
# File 'lib/alba/resource.rb', line 647

def prefer_object_method!
  alias_method :fetch_attribute_from_object_and_resource, :_fetch_attribute_from_object_first
end

#prefer_resource_method!void

This method returns an undefined value.

DSL for alias, purely for readability



641
642
643
# File 'lib/alba/resource.rb', line 641

def prefer_resource_method!
  alias_method :fetch_attribute_from_object_and_resource, :_fetch_attribute_from_resource_first
end

#root_key(key, key_for_collection = nil) ⇒ void

This method returns an undefined value.

Set root key

Parameters:

  • key (String, Symbol)
  • key_for_collection (String, Symbol) (defaults to: nil)

Raises:

  • (NoMethodError)

    when key doesn’t respond to ‘to_sym` method



513
514
515
516
# File 'lib/alba/resource.rb', line 513

def root_key(key, key_for_collection = nil)
  @_key = key.to_sym
  @_key_for_collection = key_for_collection&.to_sym
end

#root_key!void

This method returns an undefined value.

Set root key to true



530
531
532
533
# File 'lib/alba/resource.rb', line 530

def root_key!
  @_key = true
  @_key_for_collection = true
end

#root_key_for_collection(key) ⇒ void

This method returns an undefined value.

Set root key for collection

Parameters:

  • key (String, Symbol)

Raises:

  • (NoMethodError)

    when key doesn’t respond to ‘to_sym` method



523
524
525
526
# File 'lib/alba/resource.rb', line 523

def root_key_for_collection(key)
  @_key = true
  @_key_for_collection = key.to_sym
end

#trait(name, &block) ⇒ void

This method returns an undefined value.

Set a trait

Parameters:

  • name (String, Symbol)

    name of the trait

  • block (Block)

    the “content” of the trait

Raises:

  • (ArgumentError)

    if block is absent



500
501
502
503
504
505
# File 'lib/alba/resource.rb', line 500

def trait(name, &block)
  raise ArgumentError, 'No block given in trait method' unless block

  name = name.to_sym
  @_traits[name] = block
end

#transform_keys(type, root: true, cascade: true) ⇒ void

This method returns an undefined value.

Transform keys as specified type

Parameters:

  • type (String, Symbol)

    one of ‘snake`, `:camel`, `:lower_camel`, `:dash` and `none`

  • root (Boolean) (defaults to: true)

    decides if root key also should be transformed

  • cascade (Boolean) (defaults to: true)

    decides if key transformation cascades into inline association Default is true but can be set false for old (v1) behavior

Raises:



558
559
560
561
562
563
564
565
566
567
568
# File 'lib/alba/resource.rb', line 558

def transform_keys(type, root: true, cascade: true)
  type = type.to_sym
  unless %i[none snake camel lower_camel dash].include?(type)
    # This should be `ArgumentError` but for backward compatibility it raises `Alba::Error`
    raise ::Alba::Error, "Unknown transform type: #{type}. Supported type are :camel, :lower_camel and :dash."
  end

  @_transform_type = type
  @_transforming_root_key = root
  @_key_transformation_cascade = cascade
end

#transform_keys!(type) ⇒ Object

Transform keys as specified type AFTER the class is defined Note that this is an experimental API and may be removed/changed

See Also:



574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/alba/resource.rb', line 574

def transform_keys!(type)
  dup.class_eval do
    transform_keys(type, root: @_transforming_root_key, cascade: @_key_transformation_cascade)

    if @_key_transformation_cascade
      # We need to update key transformation of associations and nested attributes
      @_attributes.each_value do |attr|
        attr.key_transformation = type if attr.is_a?(Association) || attr.is_a?(NestedAttribute)
      end
    end
    self # Return the new class
  end
end