Skip to content

Commit

Permalink
Merge b25d666 into b990f27
Browse files Browse the repository at this point in the history
  • Loading branch information
gburgett committed May 10, 2019
2 parents b990f27 + b25d666 commit 4f4381d
Show file tree
Hide file tree
Showing 24 changed files with 2,840 additions and 77 deletions.
17 changes: 4 additions & 13 deletions .rubocop.yml
Expand Up @@ -45,14 +45,6 @@ Style/ClassAndModuleChildren:
Style/FormatStringToken:
EnforcedStyle: template

Metrics/BlockLength:
Exclude:
# config files where we expect long blocks
- '*/*.gemspec'
# spec files that might have a big describe
- '*/spec/**/*.rb'
# dsl files https://stackoverflow.com/a/41187163

Metrics/CyclomaticComplexity:
Enabled: false

Expand All @@ -74,10 +66,6 @@ Metrics/ClassLength:
Metrics/ModuleLength:
Enabled: false

Performance/UnfreezeString:
Exclude:
- '*/spec/**/*.rb'

Style/BracesAroundHashParameters:
Enabled: false

Expand Down Expand Up @@ -110,7 +98,10 @@ Style/SignalException:
Layout/AlignParameters:
EnforcedStyle: with_fixed_indentation

Layout/IndentHash:
Layout/AlignArguments:
EnforcedStyle: with_fixed_indentation

Layout/IndentFirstHashElement:
EnforcedStyle: consistent

Layout/AlignHash:
Expand Down
Expand Up @@ -116,13 +116,15 @@ def combine_individual_classes_to_one_string(classes)
class_string
end

def safe_line_break(text)
def safe_line_break(text, options = {})
return unless text.present?

text = CGI.escapeHTML(text)
text = text.gsub(/\&(nbsp|vert|\#\d+);/, '&\1;')
.gsub(/\&lt;br\/?\&gt;/, '<br/>')
content_tag(:span, text.html_safe, class: 'safe-line-break')
content_tag(:span, text.html_safe, {
class: 'safe-line-break'
}.merge(options))
end

def split_content_for_mobile_view(visible_count, speakers)
Expand Down
2 changes: 1 addition & 1 deletion wcc-contentful-app/wcc-contentful-app.gemspec
Expand Up @@ -12,7 +12,7 @@ Gem::Specification.new do |spec|

spec.summary = File.readlines(File.expand_path('README.md', __dir__)).join
spec.description = 'Models, Controllers, and Views common to Watermark Church apps'
spec.homepage = 'https://github.com/watermarkchurch/wcc-contentful/wcc-cms'
spec.homepage = 'https://github.com/watermarkchurch/wcc-contentful/wcc-contentful-app'
spec.license = 'MIT'

spec.required_ruby_version = '>= 2.3'
Expand Down
4 changes: 4 additions & 0 deletions wcc-contentful-graphql/.rspec
@@ -0,0 +1,4 @@
--require spec_helper
--format documentation
--color
--order rand
8 changes: 8 additions & 0 deletions wcc-contentful-graphql/Gemfile
@@ -0,0 +1,8 @@
# frozen_string_literal: true

source 'https://rubygems.org'

# Specify your gem's dependencies in wcc-contentful.gemspec
gemspec

gem 'wcc-contentful', path: File.expand_path('../wcc-contentful', __dir__)
101 changes: 101 additions & 0 deletions wcc-contentful-graphql/Guardfile
@@ -0,0 +1,101 @@
# A guardfile for making Danger Plugins
# For more info see https://github.com/guard/guard#readme

# To run, use `bundle exec guard`.

def watch_async(regexp)
raise ArgumentError, "No block given" unless block_given?
match_queue = Queue.new

watch(regexp) do |match|
# Producer - add matches to the match queue
match_queue << match
nil
end

# Consumer - process matches as a batch
Thread.new do
loop do
matches = []
matches << match_queue.pop

loop do
begin
matches << match_queue.pop(true)
rescue ThreadError
break
end
end

begin
yield matches if matches.length > 0
rescue StandardError => ex
STDERR.puts "Error! #{ex}"
end
end
end
end

group :red_green_refactor, halt_on_fail: true do
guard :rspec, cmd: 'bundle exec rspec' do
require 'guard/rspec/dsl'
dsl = Guard::RSpec::Dsl.new(self)

# RSpec files
rspec = dsl.rspec
watch(rspec.spec_helper) { rspec.spec_dir }
# watch(rspec.spec_support) { rspec.spec_dir }
watch(rspec.spec_files)

# Ruby files
ruby = dsl.ruby
watch(%r{lib/wcc/(.+)\.rb$}) { |m| rspec.spec.call("wcc/#{m[1]}") }
watch(%r{lib/generators/(.+)\.rb$}) { |m| rspec.spec.call("generators/#{m[1]}") }

# Rails files
rails = dsl.rails(view_extensions: %w[erb haml slim])
dsl.watch_spec_files_for(rails.app_files)
dsl.watch_spec_files_for(rails.views)

watch(rails.controllers) do |m|
[
rspec.spec.call("routing/#{m[1]}_routing"),
rspec.spec.call("controllers/#{m[1]}_controller"),
rspec.spec.call("acceptance/#{m[1]}")
]
end

# Rails config changes
watch(rails.spec_helper) { rspec.spec_dir }
watch(rails.routes) { "#{rspec.spec_dir}/routing" }
watch(rails.app_controller) { "#{rspec.spec_dir}/controllers" }

# Capybara features specs
watch(rails.view_dirs) { |m| rspec.spec.call("features/#{m[1]}") }
watch(rails.layouts) { |m| rspec.spec.call("features/#{m[1]}") }
end

guard :rubocop, cli: ['--display-cop-names'] do
watch(%r{.+\.rb$})
watch(%r{(?:.+/)?\.rubocop(?:_todo)?\.yml$}) { |m| File.dirname(m[0]) }
end

guard :shell, all_on_start: false do
watch_async(%r{app/views/(.+\.html.*\.erb)}) { |matches|

matches = matches.map { |m| File.absolute_path(m[0]) }
Dir.chdir('..') {
system("bundle exec erblint #{matches.join(' ')}")
}
}
end
end

group :autofix do
guard :rubocop, all_on_start: false, cli: ['--auto-correct', '--display-cop-names'] do
watch(%r{.+\.rb$})
watch(%r{(?:.+/)?\.rubocop(?:_todo)?\.yml$}) { |m| File.dirname(m[0]) }
end
end

scope group: :red_green_refactor
5 changes: 5 additions & 0 deletions wcc-contentful-graphql/README.md
@@ -0,0 +1,5 @@
[![Gem Version](https://badge.fury.io/rb/wcc-contentful-graphql.svg)](https://rubygems.org/gems/wcc-contentful-graphql)
[![Build Status](https://travis-ci.org/watermarkchurch/wcc-contentful.svg?branch=master)](https://travis-ci.org/watermarkchurch/wcc-contentful)
[![Coverage Status](https://coveralls.io/repos/github/watermarkchurch/wcc-contentful/badge.svg?branch=master)](https://coveralls.io/github/watermarkchurch/wcc-contentful?branch=master)

# WCC::Contentful::Graphql
124 changes: 124 additions & 0 deletions wcc-contentful-graphql/Rakefile
@@ -0,0 +1,124 @@
# frozen_string_literal: true

require 'bundler/setup'
require 'fileutils'

require 'wcc/contentful'

# rubocop:disable Metrics/LineLength
# Disabling line length for contentful-schema-diff backtick execution

namespace :app do
desc "Imports a set of models from a space as a single template for the ModelGenerator.\n" \
'Usage: rake wcc:import_model[content-type-id,space-id?,extra-content-type-1,extra-content-type-2...]'
task :import_model, [:model, :space] do |_t, args|
raise ArgumentError, 'Must give a content type' unless model = args[:model]

singular = model.downcase.singularize
plural = model.downcase.pluralize

all_models = [model, *args.extras]

unless space = args[:space].presence
space = ENV['CONTENTFUL_SPACE_ID']
space = "#{space}/#{ENV['CONTENTFUL_ENVIRONMENT']}" if ENV['CONTENTFUL_ENVIRONMENT']
end
raise ArgumentError, 'Must provide a space' unless space
unless mgmt_token = ENV['CONTENTFUL_MANAGEMENT_TOKEN']
raise ArgumentError, 'Must set CONTENTFUL_MANAGEMENT_TOKEN envvar'
end

client = WCC::Contentful::SimpleClient::Management.new(
space: space.split('/').first,
environment: space.split('/')[1],
management_token: mgmt_token
)

# Update the `content_types_mgmt_api.json` which we use to generate models in specs
content_types = JSON.parse(File.read('spec/fixtures/contentful/content_types_mgmt_api.json'))
all_models.each do |model_id|
content_type = client.content_type(model_id).raw

if index = content_types['items'].find_index { |ct| ct.dig('sys', 'id').casecmp(model_id) == 0 }
content_types['items'][index] = content_type
else
content_types['items'].push(content_type)
end
end
File.write('spec/fixtures/contentful/content_types_mgmt_api.json',
JSON.pretty_generate(content_types))

# Make the generator directory
FileUtils.mkdir_p("lib/generators/wcc/templates/#{singular}/models")

# Generate a migration for the content type
File.write('empty-export.json', <<~HEREDOC)
{
"contentTypes": [],
"editorInterfaces": [],
"entries": [],
"assets": [],
"locales": []
}
HEREDOC
begin
result = `contentful-schema-diff --from empty-export.json --to #{space} #{all_models.map { |m| "-c #{m}" }.join(' ')} -a '#{mgmt_token}' --out './' --one-file`
result = result.strip
raise StandardError, 'Error writing diff!' unless result.present?

FileUtils.mv(result, "lib/generators/wcc/templates/#{singular}/generated_add_#{plural}.ts")
ensure
File.unlink('empty-export.json')
end

const = WCC::Contentful::Helpers.constant_from_content_type(model)

# Write a model for the content type
File.write("lib/generators/wcc/templates/#{singular}/models/#{singular.tr('-', '_')}.rb", <<~HEREDOC)
# frozen_string_literal: true
# This model represents the '#{model}' content type in Contentful. Any linked
# entries of the '#{model}' content type will be resolved as instances of this class.
# It exposes .find, .find_by, and .find_all methods to query Contentful.
class #{const} < WCC::Contentful::Model::#{const}
# Add custom validations to ensure that app-specific properties exist:
# validate_field :foo, :String, :required
# validate_field :bar_links, :Array, link_to: %w[bar baz]
# Override functionality or add utilities
#
# # Example: override equality
# def ===(other)
# ...
# end
#
# # Example: override "title" attribute to always be titlecase.
# # `@title` is populated by the gem in the initializer.
# def title
# @title_titlecased ||= @title.titlecase
# end
end
HEREDOC

view_name = const.demodulize.underscore.sub('section_', '')
FileUtils.touch("app/views/sections/_#{view_name}.html.erb")
File.write("spec/views/sections/_#{view_name}.html.erb_spec.rb", <<~HEREDOC)
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'sections/#{view_name}' do
helper WCC::Contentful::App::SectionHelper
it 'renders successfully' do
section = contentful_create('#{model}')
render partial: 'components/section', locals: { section: section }
expect(rendered).to have_css('section.#{model}.default')
end
end
HEREDOC
end
end

# rubocop:enable Metrics/LineLength

0 comments on commit 4f4381d

Please sign in to comment.