First commit

This commit is contained in:
Tim Kächele 2021-06-06 11:41:55 +02:00
commit 0dd62e5d54
23 changed files with 800 additions and 0 deletions

18
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,18 @@
name: Ruby
on: [push,pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.0.0
- name: Run the default task
run: |
gem install bundler -v 2.2.2
bundle install
bundle exec rake

11
.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
# rspec failure tracking
.rspec_status

3
.rspec Normal file
View File

@ -0,0 +1,3 @@
--format documentation
--color
--require spec_helper

10
.rubocop.yml Normal file
View File

@ -0,0 +1,10 @@
Style/StringLiterals:
Enabled: true
EnforcedStyle: double_quotes
Style/StringLiteralsInInterpolation:
Enabled: true
EnforcedStyle: double_quotes
Layout/LineLength:
Max: 120

84
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,84 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mail@timkaechele.me. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.

6
Gemfile Normal file
View File

@ -0,0 +1,6 @@
# frozen_string_literal: true
source "https://rubygems.org"
# Specify your gem's dependencies in liquid_dynamic_context.gemspec
gemspec

71
Gemfile.lock Normal file
View File

@ -0,0 +1,71 @@
PATH
remote: .
specs:
liquid_dynamic_context (0.1.0)
activesupport (>= 6.0)
liquid (>= 5.0)
GEM
remote: https://rubygems.org/
specs:
activesupport (6.1.3.2)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
zeitwerk (~> 2.3)
ast (2.4.2)
concurrent-ruby (1.1.8)
diff-lcs (1.4.4)
i18n (1.8.10)
concurrent-ruby (~> 1.0)
liquid (5.0.1)
minitest (5.14.4)
parallel (1.20.1)
parser (3.0.1.1)
ast (~> 2.4.1)
rainbow (3.0.0)
rake (13.0.3)
regexp_parser (2.1.1)
rexml (3.2.5)
rspec (3.10.0)
rspec-core (~> 3.10.0)
rspec-expectations (~> 3.10.0)
rspec-mocks (~> 3.10.0)
rspec-core (3.10.1)
rspec-support (~> 3.10.0)
rspec-expectations (3.10.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.10.0)
rspec-mocks (3.10.2)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.10.0)
rspec-support (3.10.2)
rubocop (0.93.1)
parallel (~> 1.10)
parser (>= 2.7.1.5)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8)
rexml
rubocop-ast (>= 0.6.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 1.4.0, < 2.0)
rubocop-ast (1.7.0)
parser (>= 3.0.1.1)
ruby-progressbar (1.11.0)
tzinfo (2.0.4)
concurrent-ruby (~> 1.0)
unicode-display_width (1.7.0)
zeitwerk (2.4.2)
PLATFORMS
x86_64-linux
DEPENDENCIES
liquid_dynamic_context!
rake (~> 13.0)
rspec (~> 3.0)
rubocop (~> 0.80)
BUNDLED WITH
2.2.2

21
LICENSE.txt Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2021 Tim Kächele
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

126
README.md Normal file
View File

@ -0,0 +1,126 @@
# LiquidDynamicContext
This gem addresses a two common problem when dealing with applications that provide non-technical
users to customize system messages via liquid templates:
- **lack of structure** in how the context is generated, leading to a grab-bag class that does everything
- **poor performance** due to unnecessary computations to provide all variables for the context,
no matter whether they are really used
## How this gem helps you solve the problem
This gem addresses the problems stated above with the introduction of one simple structuring technique,
that allows you to group common sets of attributes in a so called `BindingResolver` that takes
care of resolving the bindings to their actual values and can determine whether it actually
needs to run in order to successfully render the template.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'liquid_dynamic_context', github: 'timkaechele/liquid_dynamic_context'
```
And then execute:
```bash
$ bundle install
```
## Usage
After the installation of the gem in your application you are ready to rumble and can start
by implementing your first `BindingResolver`
### Your first resolver
For this example we are going to assume that your liquid templates sometimes need to provide
access to the currently logged in user
```ruby
require 'liquid_dynamic_context'
# /app/messages/resolvers/user_binding_resolver.rb
class UserBindingResolver < LiquidDynamicContext::BindingResolver
# first we have state the bindings that this resolver can provide
register_binding :email, :username
protected
# In this method we do the actual work of resolving the bindings to
# their respective values
def resolve(models, context)
user = User.find(model[:current_user_id])
context.email = user.email
context.username = user.username
end
end
```
## Using the resolver
Now that we have written the first resolver it's time to wire it all up
and use our new resolver to provide a context for our template.
To do so we use the TemplateContext class.
```ruby
require 'liquid_dynamic_context'
# First we need our message template for, this example we define it
# directly in the code, later you may want to dynamically load the
# liquid template e.g. from a database table
liquid_template_string = <<~LIQUID
Hello {{ username }},
your newly assigned email address is {{ email }}.
LIQUID
# To provide the context we need to construct a template context
# which knows about all our available resolvers
template_context = LiquidDynamicContext::TemplateContext.new([UserBindingResolver.new])
# Remember that we can pass dynamic attributes to the context to resolve data on
# the fly, in this example we are going to pass in the current_user_id via a hash
models = {
current_user_id: 4902,
}
# Only the resolvers that are responsible for providing the variables mentioned
# in the template are actually run.
bindings = template_context.resolve(liquid_template_string, models)
# => { "username" => "Steve_Smith", "email" => "steve.smith123@example.com" }
```
Now that we have our bindings for the liquid template we can render our liquid template as usual.
```ruby
template = Liquid::Template.parse(liquid_template_string)
template.render(bindings)
# => "
# Hello Steve_Smith,
#
# your newly assigned email address is steve.smith123@example.com.
# "
```
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/timkaechele/liquid_dynamic_context. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/timkaechele/liquid_dynamic_context/blob/master/CODE_OF_CONDUCT.md).
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
## Code of Conduct
Everyone interacting in the LiquidDynamicContext project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/timkaechele/liquid_dynamic_context/blob/master/CODE_OF_CONDUCT.md).

12
Rakefile Normal file
View File

@ -0,0 +1,12 @@
# frozen_string_literal: true
require "bundler/gem_tasks"
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
require "rubocop/rake_task"
RuboCop::RakeTask.new
task default: %i[spec rubocop]

15
bin/console Executable file
View File

@ -0,0 +1,15 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "bundler/setup"
require "liquid_dynamic_context"
# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.
# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start
require "irb"
IRB.start(__FILE__)

8
bin/setup Executable file
View File

@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle install
# Do any other automated setup that you need to do here

View File

@ -0,0 +1,19 @@
# frozen_string_literal: true
require "active_support"
# for class_attribute method
require "active_support/core_ext/class/attribute"
# for #deep_stringify_keys
require "active_support/core_ext/hash/keys"
require "liquid"
require_relative "liquid_dynamic_context/version"
require_relative "liquid_dynamic_context/binding_resolver"
require_relative "liquid_dynamic_context/template_context"
require_relative "liquid_dynamic_context/variable_finder"
module LiquidDynamicContext
class Error < StandardError; end
# Your code goes here...
end

View File

@ -0,0 +1,28 @@
# frozen_string_literal: true
module LiquidDynamicContext
class BindingResolver
class_attribute :bindings
self.bindings = Set.new
def self.register_binding(*bindings)
self.bindings = self.bindings + bindings.to_set
end
def call(models)
context = Struct.new(*self.class.bindings).new
resolve(models, context)
context.to_h.deep_stringify_keys
end
def needs_to_run?(used_bindings)
!(bindings & used_bindings.to_set).empty?
end
protected
def resolve(models, context)
raise NotImplementedError
end
end
end

View File

@ -0,0 +1,37 @@
# frozen_string_literal: true
module LiquidDynamicContext
class TemplateContext
attr_reader :binding_resolvers,
:variable_finder
# @param binding_resolvers [Enumerable<BindingResolver>] a list of your
# binding resolver implementations
# @param variable_finder [#find_variables] an instance of an object
# that can find variables in a liquid template
def initialize(binding_resolvers, variable_finder: VariableFinder.new)
@binding_resolvers = binding_resolvers
@variable_finder = variable_finder
end
# Given a liquid template string and any object you may want to dynamically
# assign as input to variables this method returns you a list of key/value
# pairs that contain the necessary bindings for your template.
#
# @param template_string [String] a valid liquid template
# @param models [Any] an object with dynamic data you want to
# pass to your resolvers, can be nil
#
# @return a hash with string keys that contains the bindings for the template
def resolve(template_string, models)
binding_resolvers.select { |resolver| resolver.needs_to_run?(variables(template_string)) }
.map { |resolver| resolver.call(models) }
.reduce({}, &:merge!)
end
private
def variables(template_string)
variable_finder.find_variables(template_string)
end
end
end

View File

@ -0,0 +1,33 @@
# frozen_string_literal: true
module LiquidDynamicContext
class VariableFinder
# Extracts all used variables from a liquid template.
#
# @param template_string [String] a string with a valid liquid template
#
# @return an enumerable with the variables found in the template, the variables
# are represented as symbols
def find_variables(template_string)
parsed_template = Liquid::Template.parse(template_string)
variable_lookups(parsed_template)
.flatten
.compact
.map { |variable| variable.split(".").first }
.map(&:to_sym)
.uniq
end
private
def variable_lookups(parsed_template)
Liquid::ParseTreeVisitor.for(parsed_template.root)
.add_callback_for(Liquid::VariableLookup) do |node|
[node.name, *node.lookups].join(".")
end
.visit
end
end
end

View File

@ -0,0 +1,5 @@
# frozen_string_literal: true
module LiquidDynamicContext
VERSION = "0.1.0"
end

View File

@ -0,0 +1,42 @@
# frozen_string_literal: true
require_relative "lib/liquid_dynamic_context/version"
Gem::Specification.new do |spec|
spec.name = "liquid_dynamic_context"
spec.version = LiquidDynamicContext::VERSION
spec.authors = ["Tim Kächele"]
spec.email = ["mail@timkaechele.me"]
spec.summary = "Dynamically resolve your liquid variable bindings"
spec.description = ""
spec.homepage = "https://github.com/timkaechele/liquid_dynamic_context"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
# spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/timkaechele/liquid_dynamic_context.git"
spec.metadata["changelog_uri"] = "https://github.com/timkaechele/liquid_dynamic_context/releases"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# Uncomment to register a new dependency of your gem
spec.add_dependency "activesupport", ">= 6.0"
spec.add_dependency "liquid", ">= 5.0"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "rubocop", "~> 0.80"
# For more information and examples about making a new gem, checkout our
# guide at: https://bundler.io/guides/creating_gem.html
end

View File

@ -0,0 +1,58 @@
# frozen_string_literal: true
RSpec.describe LiquidDynamicContext::BindingResolver do
describe "#call" do
subject do
clazz.new.call({ my_value: "test method" })
end
let(:clazz) do
Class.new(described_class) do
register_binding :result, :result_2
protected
def resolve(models, context)
context.result = models[:my_value]
context.result_2 = models[:my_value] + " hello world"
end
end
end
it "returns a hash with the bindings" do
expect(subject).to eq({
"result" => "test method",
"result_2" => "test method hello world"
})
end
end
describe "#needs_to_run?" do
subject do
clazz.new.needs_to_run?(used_bindings)
end
let(:clazz) do
Class.new(described_class) do
register_binding :username, :testing
end
end
let(:used_bindings) { [:username] }
context "when used bindings matches available binding" do
it { is_expected.to be true }
end
context "when no used bindings are availabe" do
let(:used_bindings) { [] }
it { is_expected.to be false }
end
context "when available bindings do not contain any used bindings" do
let(:used_bindings) { [:unknown_variable] }
it { is_expected.to be false }
end
end
end

View File

@ -0,0 +1,7 @@
# frozen_string_literal: true
RSpec.describe LiquidDynamicContext do
it "has a version number" do
expect(LiquidDynamicContext::VERSION).not_to be nil
end
end

15
spec/spec_helper.rb Normal file
View File

@ -0,0 +1,15 @@
# frozen_string_literal: true
require "liquid_dynamic_context"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end

View File

@ -0,0 +1,147 @@
# frozen_string_literal: true
RSpec.describe LiquidDynamicContext::TemplateContext do
describe "#resolve" do
subject { template_context.resolve(template_string, { username: "strangertims" }) }
let(:template_context) do
described_class.new([resolver_a.new,
resolver_b.new])
end
let(:resolver_a) do
Class.new(LiquidDynamicContext::BindingResolver) do
register_binding :username,
:password
protected
def resolve(models, context)
context.username = models[:username]
context.password = "Super Secure Password"
end
end
end
let(:resolver_b) do
Class.new(LiquidDynamicContext::BindingResolver) do
register_binding :other_info
protected
def resolve(_models, context)
context.other_info = {
more_info: "Detailed INFO"
}
end
end
end
context "with no used bindings" do
let(:template_string) do
<<~TEXT
Hello World
TEXT
end
it "returns an empty hash" do
expect(subject).to be_instance_of(Hash)
expect(subject).to be_empty
end
end
context "with username variable used" do
let(:template_string) do
<<~TEXT
Good morning {{ username }},
welcome to our great product.
TEXT
end
it "returns a hash with the result of binding resolver a" do
expect(subject.keys.length).to eq(2)
expect(subject["username"]).to eq("strangertims")
expect(subject["password"]).to eq("Super Secure Password")
end
it "calls only resolver a" do
expect_any_instance_of(resolver_a).to receive(:call).and_call_original
expect_any_instance_of(resolver_b).to_not receive(:call).and_call_original
subject
end
end
context "with username variable used" do
let(:template_string) do
<<~TEXT
Good morning {{ username }},
welcome to our great product.
TEXT
end
it "returns a hash with the result of binding resolver a" do
expect(subject.keys.length).to eq(2)
expect(subject["username"]).to eq("strangertims")
expect(subject["password"]).to eq("Super Secure Password")
end
it "calls only resolver a" do
expect_any_instance_of(resolver_a).to receive(:call).and_call_original
expect_any_instance_of(resolver_b).to_not receive(:call).and_call_original
subject
end
end
context "with other info variable used" do
let(:template_string) do
<<~TEXT
{{ other_info.more_info }}
TEXT
end
it "returns a hash with the result of binding resolver b" do
expect(subject.keys.length).to eq(1)
expect(subject["other_info"]["more_info"]).to eq("Detailed INFO")
end
it "calls only resolver b" do
expect_any_instance_of(resolver_b).to receive(:call).and_call_original
expect_any_instance_of(resolver_a).to_not receive(:call).and_call_original
subject
end
end
context "with all variables used" do
let(:template_string) do
<<~TEXT
{{ username }}
{{ password }}
{{ other_info.more_info }}
TEXT
end
it "returns a hash with the result of binding resolver a and b" do
expect(subject.keys.length).to eq(3)
expect(subject["username"]).to eq("strangertims")
expect(subject["password"]).to eq("Super Secure Password")
expect(subject["other_info"]["more_info"]).to eq("Detailed INFO")
end
it "calls all available resolvers" do
expect_any_instance_of(resolver_b).to receive(:call).and_call_original
expect_any_instance_of(resolver_a).to receive(:call).and_call_original
subject
end
end
end
end

24
spec/variable_finder.rb Normal file
View File

@ -0,0 +1,24 @@
# frozen_string_literal: true
RSpec.describe LiquidDynamicContext::VariableFinder do
describe "#find_variables" do
subject { described_class.new.find_variables(template_string) }
let(:template_string) do
<<~TEXT
Hello World
{% if good_user %} {{ test_variable }} {% endif %}
{% for product in collection.products %}
{{ product.title }}
{% endfor %}
TEXT
end
it "finds all top level variables" do
expected_variables = %i[good_user test_variable product collection].to_set
expect(subject.to_set).to eq(expected_variables)
end
end
end