Module: Icalendar::HasComponents

Included in:
Component
Defined in:
lib/icalendar/has_components.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

METHOD_MISSING_ADD_REGEX =
/^add_(x_\w+)$/.freeze
METHOD_MISSING_X_FLAG_REGEX =
/^x_/.freeze

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/icalendar/has_components.rb', line 40

def method_missing(method, *args, &block)
  method_name = method.to_s
  if method_name =~ METHOD_MISSING_ADD_REGEX
    component_name = $1
    custom = args.first || Component.new(component_name, component_name.upcase)
    add_custom_component(component_name, custom, &block)
  elsif method_name =~ METHOD_MISSING_X_FLAG_REGEX && custom_component(method_name).size > 0
    custom_component method_name
  else
    super
  end
end

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
12
# File 'lib/icalendar/has_components.rb', line 7

def self.included(base)
  base.extend ClassMethods
  base.class_eval do
    attr_reader :custom_components
  end
end

Instance Method Details

#add_component(c) {|c| ... } ⇒ Object

Yields:

  • (c)


19
20
21
22
23
24
# File 'lib/icalendar/has_components.rb', line 19

def add_component(c)
  c.parent = self
  yield c if block_given?
  send("#{c.name.downcase}s") << c
  c
end

#add_custom_component(component_name, c) {|c| ... } ⇒ Object

Yields:

  • (c)


26
27
28
29
30
31
# File 'lib/icalendar/has_components.rb', line 26

def add_custom_component(component_name, c)
  c.parent = self
  yield c if block_given?
  (custom_components[component_name.downcase.gsub("-", "_")] ||= []) << c
  c
end

#custom_component(component_name) ⇒ Object



33
34
35
# File 'lib/icalendar/has_components.rb', line 33

def custom_component(component_name)
  custom_components[component_name.downcase.gsub("-", "_")] || []
end

#initialize(*args) ⇒ Object



14
15
16
17
# File 'lib/icalendar/has_components.rb', line 14

def initialize(*args)
  @custom_components = Hash.new
  super
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
# File 'lib/icalendar/has_components.rb', line 53

def respond_to_missing?(method_name, include_private = false)
  string_method = method_name.to_s
  string_method.start_with?('add_x_') || custom_component(string_method).size > 0 || super
end