Class: Sitepress::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/sitepress/model.rb

Overview

Wraps a page in a class, which makes it much easier to decorate and validate.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(page) ⇒ Model

Returns a new instance of Model.



15
16
17
# File 'lib/sitepress/model.rb', line 15

def initialize(page)
  @page = page
end

Instance Attribute Details

#pageObject (readonly)

Returns the value of attribute page.



4
5
6
# File 'lib/sitepress/model.rb', line 4

def page
  @page
end

Class Method Details

.collection(name = :all, glob: nil) ⇒ Object

Defines a class method that may be called later to return a collection of objects. The default glob, for example, is named ‘:all`, which defines `MyModel.all` on the class.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/sitepress/model.rb', line 32

def collection(name = :all, glob: nil, **, &)
  if block_given?
    build_collection(&)
  else
    ActiveSupport::Deprecation.new.warn(
      "The `collection :#{name}, glob: ...` macro is deprecated. " \
      "Use `def self.#{name} = glob('#{glob}')` instead."
    )
    define_singleton_method name do
      self.glob glob, **
    end
  end
end

.data(*keys, default: nil) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/sitepress/model.rb', line 67

def data(*keys, default: nil)
  keys.each do |key|
    define_method key do
      self.data.fetch key.to_s, default
    end
  end
end

.get(page) ⇒ Object Also known as: find

Wraps a page in a class if given a string that represents the path or a page object itself.



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/sitepress/model.rb', line 53

def get(page)
  case page
  when Model
    page
  when String
    get site.get page
  when Sitepress::Resource
    new page
  else
    nil
  end
end

.glob(glob) ⇒ Object

Adhoc querying of models via ‘Model.glob(“foo/bar”).all`



47
48
49
# File 'lib/sitepress/model.rb', line 47

def glob(glob, **)
  build_collection(model: self, **){ site.glob(glob) }
end

.siteObject



75
76
77
# File 'lib/sitepress/model.rb', line 75

def site
  Sitepress.site
end

Instance Method Details

#==(model) ⇒ Object

Treat as equal if the resource and model class are the same.



20
21
22
# File 'lib/sitepress/model.rb', line 20

def ==(model)
  self.page == model.page and self.class == model.class
end