Skip to content

Commit

Permalink
Use Kernel#format to render <img /> HTML tag (#46)
Browse files Browse the repository at this point in the history
* Use `Kernel#format` to render `<img />` HTML tag

* Remove spacer comment
  • Loading branch information
ashmaroli committed Feb 19, 2020
1 parent 0cb0735 commit c0cf216
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 19 deletions.
41 changes: 29 additions & 12 deletions lib/jekyll-avatar.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,27 @@ module Jekyll
class Avatar < Liquid::Tag
include Jekyll::LiquidExtensions

def self.generate_template_with(keys)
attrs = (BASE_ATTRIBUTES + keys).map! { |key| %(#{key}="%<#{key}>s") }.join(" ")
"<img #{attrs} />"
end
private_class_method :generate_template_with

#

SERVERS = 4
DEFAULT_SIZE = 40
API_VERSION = 3

BASE_ATTRIBUTES = %w(
class alt width height data-proofer-ignore src
).freeze

BASE_TEMPLATE = generate_template_with %w(srcset)
LAZY_TEMPLATE = generate_template_with %w(data-src data-srcset)

private_constant :BASE_ATTRIBUTES, :BASE_TEMPLATE, :LAZY_TEMPLATE

def initialize(_tag_name, text, _tokens)
super
@text = text
Expand All @@ -19,28 +36,28 @@ def initialize(_tag_name, text, _tokens)
def render(context)
@context = context
@text = @markup.render(@context)
attrs = attributes.map { |k, v| "#{k}=\"#{v}\"" }.join(" ")
"<img #{attrs} />"
template = lazy_load? ? LAZY_TEMPLATE : BASE_TEMPLATE
format(template, attributes)
end

private

def attributes
result = {
"class" => classes,
"alt" => username,
"width" => size,
"height" => size,
"data-proofer-ignore" => true
:class => classes,
:alt => username,
:width => size,
:height => size,
:"data-proofer-ignore" => true
}

if lazy_load?
result["src"] = ""
result["data-src"] = url
result["data-srcset"] = srcset
result[:src] = ""
result[:"data-src"] = url
result[:"data-srcset"] = srcset
else
result["src"] = url
result["srcset"] = srcset
result[:src] = url
result[:srcset] = srcset
end

result
Expand Down
14 changes: 7 additions & 7 deletions spec/jekyll/avatar_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,13 @@
it "builds the params" do
attrs = subject.send(:attributes)
expect(attrs).to eql({
"data-proofer-ignore" => true,
"class" => "avatar avatar-small",
"alt" => username,
"src" => src,
"srcset" => srcset,
"width" => width,
"height" => height
:"data-proofer-ignore" => true,
:class => "avatar avatar-small",
:alt => username,
:src => src,
:srcset => srcset,
:width => width,
:height => height
})
end

Expand Down

0 comments on commit c0cf216

Please sign in to comment.