Class: TinyGID

Inherits:
Object
  • Object
show all
Extended by:
MethodMissing
Includes:
MethodMissing
Defined in:
lib/tiny_gid.rb

Defined Under Namespace

Modules: MethodMissing

Constant Summary collapse

VERSION =
"0.1.2"
FORMAT =
"gid://%s/%s/%s"
REGEX =
%r{\Agid://([^/]+)/([^/]+)/([^/?]+)(?:\?(.*?))?\z}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ TinyGID

Returns a new instance of TinyGID.

Raises:

  • (ArgumentError)


79
80
81
82
# File 'lib/tiny_gid.rb', line 79

def initialize(app)
  raise ArgumentError, "app required" if app.to_s.strip.empty?
  @app = app
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *arguments, &block) ⇒ Object



95
96
97
98
99
100
101
102
# File 'lib/tiny_gid.rb', line 95

def method_missing(name, *arguments, &block)
  id = arguments.shift

  options = arguments.shift || {}
  options = options.merge(:__app__ => @app) unless options.include?(:app)

  super(name, id, options, &block)
end

Class Method Details

.app(name = nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/tiny_gid.rb', line 39

def app(name = nil)
  if block_given?
    raise ArgumentError, "block provided without an app name to scope to" unless name

    begin
      Thread.current[:__tiny_gid_app__] = name
      yield self
    ensure
      Thread.current[:__tiny_gid_app__] = nil
    end

    return
  end

  # No block but given a name, just set it :|
  @app = name if name

  case
  when Thread.current[:__tiny_gid_app__]
    Thread.current[:__tiny_gid_app__]
  when @app
    @app
  when defined?(Rails) && Rails.respond_to?(:application) && Rails.application.respond_to?(:name)
    Rails.application.name
  end
end

.app=(name) ⇒ Object

In GlobalID app names must be valid URI hostnames: alphanumeric and hyphen characters only



35
36
37
# File 'lib/tiny_gid.rb', line 35

def app=(name)
  @app = name
end

.parse(gid) ⇒ Object

Raises:

  • (ArgumentError)


66
67
68
69
70
71
72
# File 'lib/tiny_gid.rb', line 66

def parse(gid)
  raise ArgumentError, "'#{gid}' is not a valid global id" unless gid =~ REGEX

  parsed = [$1, $2, $3]
  parsed << Hash[URI.decode_www_form($4)] if $4 && !$4.empty?
  parsed
end

.to_sc(gid) ⇒ Object



74
75
76
# File 'lib/tiny_gid.rb', line 74

def to_sc(gid)
  parse(gid)[2]
end

Instance Method Details

#parse(gid) ⇒ Object

Raises:

  • (ArgumentError)


84
85
86
87
88
89
# File 'lib/tiny_gid.rb', line 84

def parse(gid)
  parsed = TinyGID.parse(gid)
  raise ArgumentError, "gid contains the wrong app: '#{parsed[0]}' must be '#@app'" unless parsed[0] == @app

  parsed
end

#to_sc(gid) ⇒ Object



91
92
93
# File 'lib/tiny_gid.rb', line 91

def to_sc(gid)
  TinyGID.to_sc(gid)
end