Module: Hallon::Linkable::ClassMethods

Defined in:
lib/hallon/linkable.rb

Overview

ClassMethods adds #from_link and #to_link DSL methods, which essentially are convenience methods for defining the way to convert a link to a pointer of a given Spotify object type.

Instance Method Summary collapse

Instance Method Details

Note:

Private API. You probably do not need to care about this method.

Defines #from_link, used in converting a link to a pointer. You can either pass it a method_name, or a type and a block.

Overloads:

  • #from_link(method_name) ⇒ Object

    Define #from_link simply by giving the name of the method, minus the link_ prefix.

    Examples:

    class Album
      include Linkable
    
      from_link :as_album # => Spotify.link_as_album(pointer, *args)
      # ^ is roughly equivalent to:
      def from_link(link, *args)
        unless link.is_a?(Spotify::Link)
          link = Link.new(link).pointer(:album)
        end
    
        Spotify.link_as_album(link)
      end
    end
  • #from_link(type) {|link, *args| ... } ⇒ Object

    Define #from_link to use the given block to convert an object from a link. The link is converted to a pointer and typechecked to be of the same type as type before given to the block.

    Examples:

    class User
      include Linkable
    
      from_link :profile do |pointer|
        Spotify.link_as_user(pointer)
      end
      # ^ is roughly equivalent to:
      def from_link(link, *args)
        unless link.is_a?(Spotify::Link)
          link = Link.new(link).pointer(:profile)
        end
    
        Spotify.link_as_user(link)
      end
    end

    Yields:

    • (link, *args)

      called when conversion is needed from Link pointer

    Yield Parameters:

    • link (Spotify::Link)
    • *args

      any extra arguments given to #from_link


67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/hallon/linkable.rb', line 67

def from_link(as_object, &block)
  block ||= Spotify.method(:"link_#{as_object}")
  type    = as_object.to_s[/^(as_)?([^_]+)/, 2].to_sym

  define_method(:from_link) do |link, *args|
    unless link.is_a?(Spotify::Link)
      link = Link.new(link).pointer(type)
    end

    instance_exec(link, *args, &block)
  end

  private :from_link
end

Defines #to_link method, used in converting the object to a Hallon::Link.

Examples:

class Artist
  include Linkable

  to_link :from_artist
  # ^ is the same as:
  def to_link(*args)
    link = Spotify.link_create_from_artist(pointer, *args)
    Link.new(link)
  end
end

98
99
100
101
102
103
# File 'lib/hallon/linkable.rb', line 98

def to_link(cmethod)
  define_method(:to_link) do |*args|
    link = Spotify.__send__(:"link_create_#{cmethod}", pointer, *args)
    Link.from(link)
  end
end