Module: Kaicho

Defined in:
lib/kaicho.rb,
lib/kaicho/util.rb,
lib/kaicho/version.rb

Overview

Kaicho is a module for instance variable management. It can also manage class variables, both are referred to as “resources.” All class and instance variables are automatically considered resources, but only those which have been defined with #def_resource have the ability to be automatically updated.

Auto-updates occur whenever a resource is updated through #update_resource or if a resource has never been initialized and is accessed through a kaicho ##attr_reader.

Note that all methods act on instances of Classes at the moment.

Defined Under Namespace

Modules: Util

Constant Summary collapse

VERSION =

Version of Kaicho

'0.3.1'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append_features(rcvr) ⇒ Object

Called when Kaicho is ‘include`d if you use the provided class methods, be sure to call super in your initialize method, otherwise they will have no effect



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/kaicho.rb', line 21

def self.append_features(rcvr)
  super

  rcvr.instance_variable_set(:@class_resources, [])
  rcvr.instance_variable_set(:@class_triggers, [])

  # @see #def_resource
  rcvr.define_singleton_method(:def_resource) do |*args, &block|
    @class_resources << [args, block]
  end

  # @see #add_triggers
  rcvr.define_singleton_method(:add_triggers) do |*triggers|
    @triggers += triggers
  end
end

Instance Method Details

#add_triggers(*trigs) ⇒ True

adds trigger(s) which can be used to trigger updates of resources who have the trigger set

Parameters:

  • trigs ([Symbol])

    a list of symbols to be used as triggers

Returns:

  • (True)

    this method always returns true or raises an exception



52
53
54
55
56
57
# File 'lib/kaicho.rb', line 52

def add_triggers(*trigs)
  @triggers ||= []
  @triggers += trigs.map(&:to_sym)

  true
end

#attr_accessor(dname, share: nil) ⇒ True

makes both an attr_reader and an attr_writer for the dname

Parameters:

  • dname

    the resource to create accessors for

  • share (defaults to: nil)

    the owner of the shared variable

Returns:

  • (True)

    this method always returns true or raises an exception



64
65
66
67
68
69
# File 'lib/kaicho.rb', line 64

def attr_accessor(dname, share: nil)
  attr_reader(dname, share: share)
  attr_writer(dname, share: share)

  true
end

#attr_reader(dname, share: nil) ⇒ True

defines an attr_reader singleton method for a resource which functions just like a typical attr_reader but will update the resource if it hasn’t been accessed before. Unlike an attr_writer, an attr_reader can only be defined for resources that have been previously defined using #def_resource.

Parameters:

  • dname

    the resource that will be accessed, as well as the name of the singleton method.

  • share (defaults to: nil)

    the owner of the shared variable

Returns:

  • (True)

    this method always returns true or raises an exception



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/kaicho.rb', line 81

def attr_reader(dname, share: nil)
  @resources ||= {}

  unless @resources.key?(dname)
    raise(ArgumentError, "resource #{dname} has not been defined")
  end

  read =
    if share.nil?
      -> { instance_variable_get(:"@#{dname}") }
    else
      -> { share.class_variable_get(:"@@#{dname}") }
    end

  define_singleton_method(dname) do
    update_depends(dname)
    update_resource(dname, rand) unless resource_defined?(dname)
    read.call
  end

  true
end

#attr_writer(dname, share: nil) ⇒ True

defines an attr_writer singleton method for a resource which functions just like a typical attr_writer but will update the resource’s dependants when it is called. Unlike an attr_reader, the resource dname need not be previously defined using #def_resource.

Parameters:

  • dname

    the resource that will be accessed. The name of the singleton method defined will be “#{dname}=”.

  • share (defaults to: nil)

    the owner of the shared variable

Returns:

  • (True)

    this method always returns true or raises an exception



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/kaicho.rb', line 113

def attr_writer(dname, share: nil)
  write =
    if share.nil?
      ->(v) { instance_variable_set(:"@#{dname}", v) }
    else
      ->(v) { share.class_variable_set(:"@@#{dname}", v) }
    end

  read =
    if share.nil?
      -> { instance_variable_get(:"@#{dname}") }
    else
      -> { share.class_variable_get(:"@@#{dname}") }
    end

  define_singleton_method(:"#{dname}=") do |v|
    if resource_defined?(dname) && read.call == v
      return v
    end

    write.call(v)
    update_dependants(dname, rand)
    v
  end

  true
end

#def_resource(dname, depends: {}, triggers: [], overwrite: false, share: nil, accessor: :read, accessors: nil, &block) ⇒ True

Define a resource

Parameters:

  • dname (Symbol)

    the name of the resource

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

    a hash of dependants with the format { dependant_name: :update_action } where update_action is the action that is taken when this resource is updated. Update_action can be one of:

    • :update - update the dependant before updating this resource

    • :keep - keep the dependant if it is already defined, otherwise, update it

    • :fail - don’t try to update this resource if the dependant is not defined

  • triggers (Array) (defaults to: [])

    a list of triggers. These triggers must have been previously defined using #add_triggers

  • overwrite (Boolean) (defaults to: false)

    if a resource with this name already exists, should it be overwritten

  • share (Object, nil) (defaults to: nil)

    if nil, this resource is stored as an instance variable, else the value must be an instance of a class and this resource is stored as a class variable owned by the class specified.

  • accessor (Symbol) (defaults to: :read)

    a symbol that determines which attribute accessors should be generated for this resource

  • accessors (Symbol) (defaults to: nil)

    alias to accessor

  • block

    a block that will be called, with no arguments, to update this resource

Returns:

  • (True)

    this method always returns true or raises an exception



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/kaicho.rb', line 169

def def_resource(dname,
                 depends:   {},
                 triggers:  [],
                 overwrite: false,
                 share:     nil,
                 accessor:  :read,
                 accessors: nil,
                 &block)
  @resources ||= {}

  accessor = accessors unless accessors.nil?

  Kaicho::Util.check_type(Symbol, dname)
  Kaicho::Util.check_type(Hash, depends)
  Kaicho::Util.check_type(Array, triggers)

  block = nil unless block_given?

  unless %i[read r write w both rw none].include?(accessor)
    raise(ArgumentError, "invalid accessor: :#{accessor}")
  end

  add_triggers # initialize @triggers to []
  triggers.each do |t|
    raise(ArgumentError, "invalid trigger :#{t}") unless @triggers.include?(t)
  end

  return if @resources.key?(dname) && !overwrite

  @resources[dname] = {
    depends:  depends,
    proc:     block,
    udid:     -1,
    triggers: triggers,
    share:    share,
    varname:  share.nil? ? "@#{dname}" : "@@#{dname}"
  }

  case accessor
  when :read,  :r
    attr_reader(dname, share: share)
  when :write, :w
    attr_writer(dname, share: share)
  when :both,  :rw
    attr_accessor(dname, share: share)
  end

  true
end

#initializeObject



38
39
40
41
42
43
44
45
# File 'lib/kaicho.rb', line 38

def initialize
  (self.class.instance_variable_get(:@class_resources))
    .each { |args, block| def_resource(*args, &block) }

  add_triggers(*(self.class.instance_variable_get(:@class_triggers)))

  super
end

#resource_defined?(dname) ⇒ True

Determine if the value for resource has been defined. In other words, determine if a resource has ever been updated.

If this resource has been defined using #def_resource then check if an associated instance or class variable is defined. Otherwise this method is eqivalent to calling instance_variable_defined?(“@#{dname}”).

Parameters:

  • dname (Symbol)

    the name of the resource

Returns:

  • (True)

    this method always returns true or raises an exception



228
229
230
231
232
233
234
235
236
237
238
# File 'lib/kaicho.rb', line 228

def resource_defined?(dname)
  return instance_variable_defined?("@#{dname}") unless @resources.key?(dname)

  if @resources[dname][:share].nil?
    instance_variable_defined?(@resources[dname][:varname])
  else
    @resources[dname][:share].class_variable_defined?(
      @resources[dname][:varname]
    )
  end
end

#resource_rootsArray

Determine the root resources of the current object

A resource is a root resource if it either does not depend on anything or all of its dependencies have the :fail action (i.e. they are not managed by kaicho)

Returns:

  • (Array)

    an array of Symbol where each element is the name of a resource root



361
362
363
364
365
# File 'lib/kaicho.rb', line 361

def resource_roots
  @resources.select do |a, attr|
    attr[:depends].empty? || attr[:depends].all? { |_,a| a == :fail }
  end.map { |a, _| a  }
end

#trigger_resources(trigger) ⇒ True

Trigger resource updates

This method will update all resources that have trigger in their list of triggers.

Parameters:

  • trigger (Symbol)

    the name of the trigger to trigger

Returns:

  • (True)

    this method always returns true or raises an exception



332
333
334
335
336
337
338
# File 'lib/kaicho.rb', line 332

def trigger_resources(trigger)
  udid = rand
  res = @resources.select { |_, v| v[:triggers].include?(trigger) }
  res.each { |r, _| update_resource(r, udid) }

  true
end

#update_all_resourcesTrue

Update all resources

Equivalent to calling #update_resource for each resource in @resources.

Returns:

  • (True)

    this method always returns true or raises an exception



345
346
347
348
349
350
351
# File 'lib/kaicho.rb', line 345

def update_all_resources
  udid = rand

  resource_roots.each { |d| update_resource(d, udid) }

  true
end

#update_dependants(dname, udid = nil) ⇒ True

Update the dependants of dname

This method will update all resources that have dname in their list of depends.

Parameters:

  • dname

    the name of the resource

  • udid (defaults to: nil)

    the update-id of this call, this should be left nil. It is internally to avoid infinite loops during update cascades.

Returns:

  • (True)

    this method always returns true or raises an exception



316
317
318
319
320
321
322
323
# File 'lib/kaicho.rb', line 316

def update_dependants(dname, udid = nil)
  udid ||= rand
  @resources.select do |_, v|
    v[:depends].include?(dname) && v[:udid] != udid
  end.each { |d, _| update_resource(d, udid) }

  true
end

#update_depends(dname, udid = nil) ⇒ bool

Update the prerequisites of a resource.

This method will update all resources that dname depends on.

Parameters:

  • dname

    the name of the resource

  • udid (defaults to: nil)

    the update-id of this call, this should be left nil. It is internally to avoid infinite loops during update cascades.

Returns:

  • (bool)

    returns false if the resource could not be found, else return true



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/kaicho.rb', line 288

def update_depends(dname, udid = nil)
  udid ||= rand
  @resources[dname][:depends].each do |d, o|
    case o
    when :update
      update_resource(d, udid)
    when :keep
      update_resource(d, udid) unless resource_defined?(d)
    when :fail
      return false unless resource_defined?(d)
    when Proc, UnboundMethod, Method
      o = o.bind(self) if o.is_a?(UnboundMethod)
      update_resource(d, udid) if o.call
    end
  end

  true
end

#update_resource(dname, udid = nil) ⇒ True

Update a resource

This method will update the specified resource and all of its depends and dependants.

Parameters:

  • dname

    the name of the resource

  • udid (defaults to: nil)

    the update-id of this call, this should be left nil. It is internally to avoid infinite loops during update cascades.

Returns:

  • (True)

    this method always returns true or raises an exception

See Also:



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/kaicho.rb', line 252

def update_resource(dname, udid = nil)
  unless @resources.key?(dname)
    raise(ArgumentError, "no such resource #{dname}")
  end

  return if @resources[dname][:udid] == udid
  udid ||= rand
  @resources[dname][:udid] = udid

  return unless update_depends(dname, udid)

  unless @resources[dname][:proc].nil?
    result = self.instance_exec(&@resources[dname][:proc])

    if @resources[dname][:share].nil?
      instance_variable_set(@resources[dname][:varname], result)
    else
      @resources[dname][:share].class_variable_set(
        @resources[dname][:varname], result
      )
    end
  end

  update_dependants(dname, udid)

  true
end