Class: Phlex::SGML

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/phlex/sgml.rb

Overview

**Standard Generalized Markup Language** for behaviour common to HTML and SVG.

Direct Known Subclasses

HTML, SVG

Defined Under Namespace

Modules: Attributes, Elements, SafeObject Classes: SafeValue, State

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.__compile__(method_name) ⇒ Object



436
437
438
439
# File 'lib/phlex/sgml.rb', line 436

def self.__compile__(method_name)
  path, line = instance_method(method_name).source_location
  Phlex::Compiler::Method.new(self, path, line, method_name).compile
end

.callObject

Render the view to a String. Arguments are delegated to new.



9
10
11
# File 'lib/phlex/sgml.rb', line 9

def call(...)
  new(...).call
end

.new(*a, **k, &block) ⇒ Object

Note:

The block will not be delegated to #initialize. Instead, it will be sent to #view_template when rendering.

Create a new instance of the component.



15
16
17
18
19
20
21
22
23
# File 'lib/phlex/sgml.rb', line 15

def new(*a, **k, &block)
  if block
    object = super(*a, **k, &nil)
    object.instance_exec { @_content_block = block }
    object
  else
    super
  end
end

Instance Method Details

#__map_exception__(exception) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/phlex/sgml.rb', line 441

def __map_exception__(exception)
  exception.set_backtrace(
    exception.backtrace_locations.map do |loc|
      if ((map = Phlex::Compiler::MAP[loc.path]) && (line = map[loc.lineno]))
        "[Phlex] #{loc.path}:#{line}:#{loc.label}"
      else
        "#{loc.path}:#{loc.lineno}:#{loc.label}"
      end
    end
  )

  exception
end

#cache(*cache_key, &content) ⇒ Object

Cache a block of content.

“‘ruby end “`



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/phlex/sgml.rb', line 236

def cache(*cache_key, **, &content)
  location = caller_locations(1, 1)[0]

  full_key = [
    app_version_key,                                   # invalidates the key when deploying new code in case of changes
    self.class.name,                                   # prevents collisions between classes
    (self.class.object_id if enable_cache_reloading?), # enables reloading
    location.base_label,                               # prevents collisions between different methods
    location.lineno,                                   # prevents collisions between different lines
    cache_key,                                         # allows for custom cache keys
  ].freeze

  low_level_cache(full_key, **, &content)

  nil
end

#call(buffer = +"",, context: {}, fragments: nil) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/phlex/sgml.rb', line 38

def call(buffer = +"", context: {}, fragments: nil, &)
  state = Phlex::SGML::State.new(
    user_context: context,
    output_buffer: buffer,
    fragments: fragments&.to_set,
  )

  internal_call(parent: nil, state:, &)

  state.output_buffer << state.buffer
end

#capture(*args, &block) ⇒ Object

Capture the output of the block and returns it as a string.



164
165
166
167
168
169
170
171
172
# File 'lib/phlex/sgml.rb', line 164

def capture(*args, &block)
  return "" unless block

  if args.length > 0
    @_state.capture { __yield_content_with_args__(*args, &block) }
  else
    @_state.capture { __yield_content__(&block) }
  end
end

#commentObject

Wrap the output in an HTML comment.

[MDN Docs](developer.mozilla.org/en-US/docs/Web/HTML/Comments)



134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/phlex/sgml.rb', line 134

def comment(&)
  state = @_state
  return unless state.should_render?

  buffer = state.buffer

  buffer << "<!-- "
  __yield_content__(&)
  buffer << " -->"

  nil
end

#contextObject



89
90
91
92
93
94
95
96
97
# File 'lib/phlex/sgml.rb', line 89

def context
  if rendering?
    @_state.user_context
  else
    raise Phlex::ArgumentError.new("      You can\u2019t access the context before the component has started rendering.\n    MESSAGE\n  end\nend\n")

#flushObject

Flush the current state to the output buffer.



196
197
198
# File 'lib/phlex/sgml.rb', line 196

def flush
  @_state.flush
end

#fragment(name) ⇒ Object

Define a named fragment that can be selectively rendered.



175
176
177
178
179
180
181
# File 'lib/phlex/sgml.rb', line 175

def fragment(name)
  state = @_state
  state.begin_fragment(name)
  yield
  state.end_fragment(name)
  nil
end

#internal_call(parent: nil, state: nil, &block) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/phlex/sgml.rb', line 50

def internal_call(parent: nil, state: nil, &block)
  if @_state
    raise Phlex::DoubleRenderError.new(
      "You can't render a #{self.class.name} more than once."
    )
  end

  @_state = state

  return "" unless render?

  block ||= @_content_block

  previous_phlex_component = Thread.current[:__phlex_component__]
  Thread.current[:__phlex_component__] = self

  state.around_render(self) do
    before_template(&block)

    around_template do
      if block
        view_template do |*args|
          if args.length > 0
            __yield_content_with_args__(*args, &block)
          else
            __yield_content__(&block)
          end
        end
      else
        view_template
      end
    end

    after_template(&block)
  end
ensure
  Thread.current[:__phlex_component__] = previous_phlex_component
end

#json_escape(string) ⇒ Object



288
289
290
# File 'lib/phlex/sgml.rb', line 288

def json_escape(string)
  ERB::Util.json_escape(string)
end

#low_level_cache(cache_key, **options, &content) ⇒ Object

Cache a block of content where you control the entire cache key. If you really know what you’re doing and want to take full control and responsibility for the cache key, use this method.

“‘ruby low_level_cache([Commonmarker::VERSION, Digest::MD5.hexdigest(@content)]) do

markdown(@content)

end “‘

Note: To allow you more control, this method does not take a splat of cache keys. If you need to pass multiple cache keys, you should pass an array.



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/phlex/sgml.rb', line 265

def low_level_cache(cache_key, **options, &content)
  state = @_state

  cached_buffer, fragment_map = cache_store.fetch(cache_key, **options) { state.caching(&content) }

  if state.should_render?
    fragment_map.each do |fragment_name, (offset, length, nested_fragments)|
      state.record_fragment(fragment_name, offset, length, nested_fragments)
    end
    state.buffer << cached_buffer
  else
    fragment_map.each do |fragment_name, (offset, length, nested_fragments)|
      if state.fragments.include?(fragment_name)
        state.fragments.delete(fragment_name)
        state.fragments.subtract(nested_fragments)
        state.buffer << cached_buffer.byteslice(offset, length)
      end
    end
  end

  nil
end

#plain(content) ⇒ Object

Output plain text.



106
107
108
109
110
111
112
# File 'lib/phlex/sgml.rb', line 106

def plain(content)
  unless __text__(content)
    raise Phlex::ArgumentError.new("You've passed an object to plain that is not handled by format_object. See https://rubydoc.info/gems/phlex/Phlex/SGML#format_object-instance_method for more information")
  end

  nil
end

#raw(content) ⇒ Object

Output the given safe object as-is. You may need to use safe to mark a string as a safe object.



148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/phlex/sgml.rb', line 148

def raw(content)
  case content
  when Phlex::SGML::SafeObject
    state = @_state
    return unless state.should_render?

    state.buffer << content.to_s
  when nil, "" # do nothing
  else
    raise Phlex::ArgumentError.new("You passed an unsafe object to `raw`.")
  end

  nil
end

#render(renderable = nil) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/phlex/sgml.rb', line 200

def render(renderable = nil, &)
  case renderable
  when Phlex::SGML
    renderable.internal_call(state: @_state, parent: self, &)
  when Class
    if renderable < Phlex::SGML
      render(renderable.new, &)
    end
  when Enumerable
    renderable.each { |r| render(r, &) }
  when Proc, Method
    if renderable.arity == 0
      __yield_content_with_no_yield_args__(&renderable)
    else
      __yield_content__(&renderable)
    end
  when String
    plain(renderable)
  when nil
    __yield_content__(&) if block_given?
  else
    raise Phlex::ArgumentError.new("You can't render a #{renderable.inspect}.")
  end

  nil
end

#rendering?Boolean

Returns false before rendering and true once the component has started rendering. It will not reset back to false after rendering.

Returns:

  • (Boolean)


101
102
103
# File 'lib/phlex/sgml.rb', line 101

def rendering?
  !!@_state
end

#safe(value) ⇒ Object Also known as: 🦺

Mark the given string as safe for HTML output.



184
185
186
187
188
189
190
191
# File 'lib/phlex/sgml.rb', line 184

def safe(value)
  case value
  when String
    Phlex::SGML::SafeValue.new(value)
  else
    raise Phlex::ArgumentError.new("Expected a String.")
  end
end

#to_procObject



34
35
36
# File 'lib/phlex/sgml.rb', line 34

def to_proc
  proc { |c| c.render(self) }
end

#view_templateObject



26
27
28
29
30
31
32
# File 'lib/phlex/sgml.rb', line 26

def view_template
  if block_given?
    yield
  else
    plain "Phlex Warning: Your `#{self.class.name}` class doesn't define a `view_template` method. If you are upgrading to Phlex 2.x make sure to rename your `template` method to `view_template`. See: https://beta.phlex.fun/guides/v2-upgrade.html"
  end
end

#whitespaceObject

Output a single space character. If a block is given, a space will be output before and after the block.



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/phlex/sgml.rb', line 115

def whitespace(&)
  state = @_state
  return unless state.should_render?

  buffer = state.buffer

  buffer << " "

  if block_given?
    __yield_content__(&)
    buffer << " "
  end

  nil
end