repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
boost/consyncful
lib/consyncful.rb
# frozen_string_literal: true require 'consyncful/version' require 'mongoid' require 'contentful' require 'consyncful/base' require 'consyncful/sync' require 'consyncful/railtie' if defined?(Rails) module Consyncful # Handles Rails configurations for Consynful class Configuration attr_accessor :contentful_client_options, :locale, :mongo_client, :mongo_collection def initialize @contentful_client_options = { api_url: 'cdn.contentful.com' } @locale = 'en-NZ' @mongo_client = :default @mongo_collection = 'contentful_models' end end DEFAULT_CLIENT_OPTIONS = { reuse_entries: true, api_url: 'cdn.contentful.com' }.freeze class << self def configuration @configuration ||= Configuration.new end def configure yield configuration end def client @client ||= begin options = Consyncful.configuration.contentful_client_options options.reverse_merge!(DEFAULT_CLIENT_OPTIONS) Contentful::Client.new(options) end end end end
boost/consyncful
spec/consyncful/persisted_item_spec.rb
<reponame>boost/consyncful<gh_stars>1-10 # frozen_string_literal: true require 'spec_helper' RSpec.describe Consyncful::PersistedItem do let(:stats) { instance_double('Consyncful::Stats') } let(:sync_id) { rand(100..200) } let(:persisted_item) { Consyncful::PersistedItem.new(item, sync_id, stats) } context 'when the item is a deletion' do let(:item) { instance_double('Consyncful::ItemMapper', deletion?: true, id: 'itemId') } let(:instance) { instance_double('Consyncful::Base') } before do allow(stats).to receive(:record_deleted) end it 'finds the model and destroys it' do expect(Consyncful::Base).to receive(:find_by).with(id: 'itemId').and_return(instance) expect(instance).to receive(:destroy) persisted_item.persist end end context 'when the item is a create or update' do let(:mapped_fields) { { field_name: 'value', other_field: 3 } } let(:item) { instance_double('Consyncful::ItemMapper', deletion?: false, id: 'itemId', type: 'itemType', mapped_fields: mapped_fields) } let(:instance) { instance_double('Consyncful::Base', persisted?: false, save: true, :[]= => nil, attributes: []) } before do allow(stats).to receive(:record_added) end # rubocop:disable Style/ClassAndModuleChildren class self::TestContentfulType < Consyncful::Base contentful_model_name 'itemType' end # rubocop:enable Style/ClassAndModuleChildren let(:klass) { self.class::TestContentfulType } it 'finds the model of the correct type' do expect(klass).to receive(:find_or_initialize_by).with(id: 'itemId').and_return(instance) persisted_item.persist end it 'assigns all mapped fields' do allow(klass).to receive(:find_or_initialize_by).with(id: 'itemId').and_return(instance) expect(instance).to receive(:[]=).with(:field_name, 'value') expect(instance).to receive(:[]=).with(:other_field, 3) persisted_item.persist end it 'sets the sync id on the item' do allow(klass).to receive(:find_or_initialize_by).with(id: 'itemId').and_return(instance) expect(instance).to receive(:[]=).with(:sync_id, sync_id) persisted_item.persist end it 'nils all other fields' do skip 'need this test' end it 'saves the item' do allow(klass).to receive(:find_or_initialize_by).with(id: 'itemId').and_return(instance) expect(instance).to receive(:save) persisted_item.persist end end end
boost/consyncful
spec/consyncful/base_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe Consyncful::Base do class self::TestContentfulType < Consyncful::Base contentful_model_name 'fooBar' references_many :foos references_one :bar end class self::TestContentfulType2 < Consyncful::Base contentful_model_name 'Baz' end let(:test_klass_with_refs) { self.class::TestContentfulType } let(:test_klass) { self.class::TestContentfulType2 } describe '.contentful_model_name' do it 'creates a mapping of all contentful model names and their ruby model names' do expect(subject.model_map).to include('fooBar' => test_klass_with_refs) expect(subject.model_map).to include('Baz' => test_klass) end end describe '.references_many' do let(:referenced_items) { [test_klass.create, test_klass.create] } let(:referencing_item) { test_klass_with_refs.create(foos: referenced_items) } it 'creates a polymorphic has-and-belongs-to-many to other contentful models' do expect(referencing_item.foos).to eq referenced_items end it 'has an association extension that returns the items in the order they are appare in id array' do referencing_item.update(foo_ids: referencing_item.foo_ids.reverse) expect(referencing_item.foos.in_order).to eq referenced_items.reverse end end describe '.references_one' do let(:referenced_item) { test_klass.create } let(:referencing_item) { test_klass_with_refs.create(bar: referenced_item) } it 'creates a polymorphic belongs-to to other contentful models' do expect(referencing_item.bar).to eq referenced_item end end end
boost/consyncful
lib/consyncful/base.rb
<gh_stars>1-10 # frozen_string_literal: true module Consyncful ## # Provides common functionality of Mongoid models created from contentful # entries class Base include Mongoid::Document include Mongoid::Attributes::Dynamic cattr_accessor :model_map store_in collection: -> { Consyncful.configuration.mongo_collection }, client: -> { Consyncful.configuration.mongo_client } def self.contentful_model_name(name) self.model_map ||= {} self.model_map[name] = self end # rubocop:disable Lint/NestedMethodDefinition def self.references_many(name) has_and_belongs_to_many name.to_sym, class_name: 'Consyncful::Base', inverse_of: nil do def in_order _target.to_a.sort_by do |reference| _base[foreign_key].index(reference.id) end end end end # rubocop:enable Lint/NestedMethodDefinition def self.references_one(name) belongs_to name.to_sym, optional: true, class_name: 'Consyncful::Base' end end end
boost/consyncful
spec/consyncful/item_mapper_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe Consyncful::ItemMapper do let(:entry_json) do { 'sys' => { 'space' => { 'sys' => { 'type' => 'Link', 'linkType' => 'Space', 'id' => 'spaceId' } }, 'id' => 'itemID', 'type' => 'Entry', 'createdAt' => '2019-02-20T00:50:17.357Z', 'updatedAt' => '2019-02-20T00:50:50.052Z', 'environment' => { 'sys' => { 'id' => 'master', 'type' => 'Link', 'linkType' => 'Environment' } }, 'revision' => 43, 'contentType' => { 'sys' => { 'type' => 'Link', 'linkType' => 'ContentType', 'id' => 'typeName' } } }, 'fields' => { 'description' => { 'en-NZ' => 'Govt loan reg text' }, 'fieldWithLocales' => { 'en-NZ' => 'English value', 'mi-NZ' => 'Maori value' }, 'text' => { 'en-NZ' => { 'nodeType' => 'document', 'data' => {}, 'content' => [{ 'nodeType' => 'paragraph', 'content' => [{ 'nodeType' => 'text', 'value' => 'To register as a government loans client please fill in the form below.', 'marks' => [], 'data' => {} }], 'data' => {} }] } } } } end let(:contentful_entry) { Contentful::Entry.new(entry_json, {}, true) } let(:asset_json) do { 'sys' => { 'space' => { 'sys' => { 'type' => 'Link', 'linkType' => 'Space', 'id' => 'spaceId' } }, 'id' => 'itemId', 'type' => 'Asset', 'createdAt' => '2019-02-12T23:28:33.756Z', 'updatedAt' => '2019-02-20T02:50:59.780Z', 'environment' => { 'sys' => { 'id' => 'development', 'type' => 'Link', 'linkType' => 'Environment' } }, 'revision' => 3 }, 'fields' => { 'title' => { 'en-NZ' => 'BBBW 5009 7a01 Hero image' }, 'description' => { 'en-NZ' => 'Test' }, 'file' => { 'en-NZ' => { 'url' => 'imageUrl', 'details' => { 'size' => 196_189, 'image' => { 'width' => 1441, 'height' => 595 } }, 'fileName' => 'Hero image.jpg', 'contentType' => 'image/jpeg' }, 'mi-NZ' => { 'url' => 'maoriImageUrl', 'details' => { 'size' => 196_189, 'image' => { 'width' => 1441, 'height' => 595 } }, 'fileName' => 'Maori hero image.jpg', 'contentType' => 'image/jpeg' } } } } end let(:contentful_asset) { Contentful::Asset.new(asset_json, {}, true) } describe '#type' do context 'when the item is an entry' do let(:item) { Consyncful::ItemMapper.new(contentful_entry) } it 'type returns the contentful typeName' do expect(item.type).to eq 'typeName' end end context 'when the item is an asset' do let(:item) { Consyncful::ItemMapper.new(contentful_asset) } it 'type returns asset' do expect(item.type).to eq 'asset' end end end describe '#id' do let(:item) { Consyncful::ItemMapper.new(contentful_entry) } it 'returns the entrys id' do expect(item.id).to eq contentful_entry.id end end describe '#mapped_fields' do let(:item) { Consyncful::ItemMapper.new(contentful_entry) } let(:default_locale) { 'en-NZ' } it 'returns the generic fields' do expect(item.mapped_fields(default_locale)).to include( created_at: DateTime.parse('2019-02-20T00:50:17.357Z'), updated_at: DateTime.parse('2019-02-20T00:50:50.052Z'), revision: 43, contentful_type: 'typeName' ) end it 'returns a field called synced_at with the current time' do dummy_time = double('time') expect(Time).to receive(:current).and_return(dummy_time) expect(item.mapped_fields(default_locale)).to include(synced_at: dummy_time) end it 'returns all content model specific fields from the default locale' do expect(item.mapped_fields(default_locale)).to include( description: 'Govt loan reg text', field_with_locales: 'English value', text: { 'nodeType' => 'document', 'data' => {}, 'content' => [{ 'nodeType' => 'paragraph', 'content' => [{ 'nodeType' => 'text', 'value' => 'To register as a government loans client please fill in the form below.', 'marks' => [], 'data' => {} }], 'data' => {} }] } ) end it 'returns any additional locales mapped to fields with suffix of the locale code' do expect(item.mapped_fields(default_locale)).to include( field_with_locales_mi_nz: 'Maori value' ) end context 'when the entry includes reference fields' do before do entry_json['fields']['manyRefs'] = { 'en-NZ' => [ { 'sys' => { 'type' => 'Link', 'linkType' => 'Entry', 'id' => '5MLrvU144Mg0OQIwIyeWea' } }, { 'sys' => { 'type' => 'Link', 'linkType' => 'Entry', 'id' => '11baJLRlumIIGEqOGaUW0Y' } } ] } entry_json['fields']['oneRef'] = { 'en-NZ' => { 'sys' => { 'type' => 'Link', 'linkType' => 'Entry', 'id' => '5MLrvU144Mg0OQIwIyeWea' } } } end it 'returns many refs as an array of ids in a field the the correct name for mongoid' do expect(item.mapped_fields(default_locale)).to include(many_ref_ids: %w[5MLrvU144Mg0OQIwIyeWea 11baJLRlumIIGEqOGaUW0Y]) end it 'returns one refs as the correct name for mongoid' do expect(item.mapped_fields(default_locale)).to include(one_ref_id: '5MLrvU144Mg0OQIwIyeWea') end end context 'when the item is an asset' do let(:item) { Consyncful::ItemMapper.new(contentful_asset) } it 'returns the correct file details for the default locale' do expect(item.mapped_fields(default_locale)[:file]).to include( 'url' => 'imageUrl', 'details' => { 'size' => 196_189, 'image' => { 'width' => 1441, 'height' => 595 } }, 'fileName' => 'Hero image.jpg', 'contentType' => 'image/jpeg' ) end it 'returns the correct file details for any other locales' do expect(item.mapped_fields(default_locale)[:file_mi_nz]).to include( 'url' => 'maoriImageUrl', 'details' => { 'size' => 196_189, 'image' => { 'width' => 1441, 'height' => 595 } }, 'fileName' => 'Maori hero image.jpg', 'contentType' => 'image/jpeg' ) end end end describe '#deletion?' do it 'returns false when the item is an Entry or Asset' do expect(Consyncful::ItemMapper.new(contentful_entry).deletion?).to eq false expect(Consyncful::ItemMapper.new(contentful_asset).deletion?).to eq false end context 'when the item is a DeletedEntry or an DeletedAsset' do let(:deleted_item_json) do { 'sys' => { 'type' => 'DeletedEntry', 'id' => 'itemID', 'space' => { 'sys' => { 'type' => 'Link', 'linkType' => 'Space', 'id' => 'spaceId' } }, 'environment' => { 'sys' => { 'id' => 'master', 'type' => 'Link', 'linkType' => 'Environment' } }, 'revision' => 1, 'createdAt' => '2019-02-20T18:25:21.515Z', 'updatedAt' => '2019-02-20T18:25:21.515Z', 'deletedAt' => '2019-02-20T18:25:21.515Z' } } end it 'returns true' do deleted_item = Contentful::DeletedEntry.new(deleted_item_json, {}, true) deleted_item_json['sys']['type'] = 'DeletedAsset' deleted_asset = Contentful::DeletedAsset.new(deleted_item_json, {}, true) expect(Consyncful::ItemMapper.new(deleted_item).deletion?).to eq true expect(Consyncful::ItemMapper.new(deleted_asset).deletion?).to eq true end end end end
boost/consyncful
lib/consyncful/sync.rb
<filename>lib/consyncful/sync.rb # frozen_string_literal: true require 'rainbow' require 'consyncful/item_mapper' require 'consyncful/persisted_item' require 'consyncful/stats' require 'hooks' module Consyncful ## # A mongoid model that stores the state of a syncronisation feed. Stores the # next URL provided by Contentfuls Sync API. # # Sync's are affectivly singletons, # there should only ever be one in the database # # Is also the entrypoint of a Syncronization run class Sync include Mongoid::Document include Hooks store_in client: -> { Consyncful.configuration.mongo_client } define_hook :before_run define_hook :after_run field :next_url field :last_run_at, type: DateTime def self.latest last || new end ## # Delete the previous sync chains from database and create a fresh one. # Used to completely resync all items from Contentful. def self.fresh destroy_all latest end ## # Makes sure that the database contains only records that have been provided # during this chain of syncronisation. def drop_stale stale = Base.where(:sync_id.ne => id, :sync_id.exists => true) puts Rainbow("Dropping #{stale.count} records that haven't been touched in this sync").red stale.destroy end ## # Entry point to a syncronization run. Is responsible for updating Sync state def run run_hook :before_run stats = Consyncful::Stats.new load_all_models sync = start_sync changed_ids = sync_items(sync, stats) drop_stale update_run(sync.next_sync_url) stats.print_stats run_hook :after_run, changed_ids end private def load_all_models return unless defined? Rails Rails.application.eager_load! end def update_run(next_url) self.next_url = next_url self.last_run_at = Time.current save end def start_sync if next_url.present? puts Rainbow("Starting update, last update: #{last_run_at} (#{(Time.current - last_run_at).round(3)}s ago)").blue Consyncful.client.sync(next_url) else puts Rainbow('Starting full refresh').blue Consyncful.client.sync(initial: true) end end def sync_items(sync, stats) ids = [] sync.each_page do |page| page.items.each do |item| ids << sync_item(ItemMapper.new(item), stats) end end ids end def sync_item(item, stats) puts Rainbow("syncing: #{item.id}").yellow PersistedItem.new(item, id, stats).persist item.id end end end
boost/consyncful
lib/consyncful/persisted_item.rb
# frozen_string_literal: true module Consyncful ## # Takes a mapped item from Contentful and creates/updates/deletes # the relevant model in the local database. class PersistedItem DEFAULT_LOCALE = 'en-NZ' def initialize(item, sync_id, stats) @item = item @sync_id = sync_id @stats = stats end def persist puts Rainbow("syncing: #{@item.id}").yellow if @item.deletion? delete_model(@item.id, @stats) else create_or_update_model(@item, @sync_id, @stats) end end private def delete_model(id, stats) Base.find_by(id: id).destroy stats.record_deleted rescue Mongoid::Errors::DocumentNotFound puts Rainbow("Deleted record not found: #{id}").yellow nil end def create_or_update_model(item, sync_id, stats) return if item.type.nil? instance = find_or_initialize_item(item) update_stats(instance, stats) reset_fields(instance) item.mapped_fields(DEFAULT_LOCALE).each do |field, value| instance[field] = value end instance[:sync_id] = sync_id instance.save end def find_or_initialize_item(item) model_class(item.type).find_or_initialize_by(id: item.id) end def update_stats(instance, stats) if instance.persisted? stats.record_updated else stats.record_added end end def model_class(type) Base.model_map[type] || Base end def reset_fields(instance) instance.attributes.each do |field_name, _value| next if field_name.in? %w[_id _type] instance[field_name] = nil end end end end
boost/consyncful
lib/consyncful/version.rb
<filename>lib/consyncful/version.rb # frozen_string_literal: true module Consyncful VERSION = '0.6.1' end
boost/consyncful
lib/consyncful/railtie.rb
# frozen_string_literal: true # Adds Consyncful task to Rails class Consyncful::Railtie < Rails::Railtie rake_tasks do load 'consyncful/tasks/consyncful.rake' end end
boost/consyncful
spec/consyncful/sync_spec.rb
<gh_stars>1-10 # frozen_string_literal: true require 'spec_helper' RSpec.describe Consyncful::Sync do describe '.drop_stale' do let(:sync1) { Consyncful::Sync.create } let(:sync2) { Consyncful::Sync.create } let!(:record1) { Consyncful::Base.create(sync_id: sync1.id) } let!(:record2) { Consyncful::Base.create(sync_id: sync1.id) } let!(:record3) { Consyncful::Base.create(sync_id: sync2.id) } it 'destroys all records that werent synced by this sync' do sync2.drop_stale expect(Consyncful::Base.count).to eq 1 expect(Consyncful::Base.all).to include(record3) end it 'does not destroy records with no sync_id' do record2.unset(:sync_id) sync2.drop_stale expect(Consyncful::Base.count).to eq 2 expect(Consyncful::Base.all).to include(record2, record3) end end describe 'callbacks' do let(:client) { instance_double('Contentful::Client', sync: client_sync) } let(:client_sync) { instance_double('Contentful::Sync', each_page: [], next_sync_url: 'next_url') } let(:sync) { Consyncful::Sync.create } before do allow(Consyncful).to receive(:client).and_return(client) end describe 'before run' do let(:callback) do proc { puts 'test before callback!' } end it 'executes hook before run' do Consyncful::Sync.before_run callback expect { sync.run }.to output(/\Atest before callback!/).to_stdout end after do Consyncful::Sync.callbacks_for_hook(:before_run).clear end end describe 'after run' do let(:page) do double('page', items: [double('item')]) end let(:mapper) { instance_double('Consyncful::ItemMapper', id: 'itemId', deletion?: true) } before do allow(client_sync).to receive(:each_page).and_yield(page) allow(Consyncful::ItemMapper).to receive(:new).and_return(mapper) end let(:callback) do proc { |ids| puts "test after callback with #{ids.join(', ')}" } end it 'executes hook after run and provides updated ids' do Consyncful::Sync.after_run callback expect { sync.run }.to output(/test after callback with #{['itemId'].join(', ')}/).to_stdout end after do Consyncful::Sync.callbacks_for_hook(:after_run).clear end end end describe '#run' do let(:client) { instance_double('Contentful::Client', sync: client_sync) } let(:client_sync) { instance_double('Contentful::Sync', each_page: [], next_sync_url: 'next_url') } before do allow(Consyncful).to receive(:client).and_return(client) end it 'starts a new sync when there is no next_url' do expect(client).to receive(:sync).with(initial: true).and_return(client_sync) Consyncful::Sync.new.run end it 'resumes sync when there is a next_url' do expect(client).to receive(:sync).with('previous_url').and_return(client_sync) Consyncful::Sync.new(next_url: 'previous_url', last_run_at: Time.now).run end it 'saves the next url' do sync = Consyncful::Sync.create sync.run expect(sync.next_url).to eq 'next_url' end it 'saves the current run time' do time = Time.current expect(Time).to receive(:current).and_return(time) sync = Consyncful::Sync.create sync.run expect(sync.last_run_at).to eq time end context 'when there are items to sync' do let(:sync) { Consyncful::Sync.create } let(:page) do double('page', items: [double('item')]) end let(:mapper) { instance_double('Consyncful::ItemMapper', id: 'itemId') } let(:persisted_item) { instance_double('Consyncful::PersistedItem') } before do allow(client_sync).to receive(:each_page).and_yield(page) allow(Consyncful::ItemMapper).to receive(:new).and_return(mapper) end it 'persists the change' do expect(Consyncful::PersistedItem).to receive(:new).with(mapper, sync.id, instance_of(Consyncful::Stats)).and_return(persisted_item) expect(persisted_item).to receive(:persist) sync.run end end end end
zhaozixiao/rubyMe
todoItems/app/graphql/todo_items_schema.rb
<reponame>zhaozixiao/rubyMe<gh_stars>0 class TodoItemsSchema < GraphQL::Schema mutation(Types::MutationType) query(Types::QueryType) # For batch-loading (see https://graphql-ruby.org/dataloader/overview.html) use GraphQL::Dataloader # GraphQL-Ruby calls this when something goes wrong while running a query: def self.type_error(err, context) # if err.is_a?(GraphQL::InvalidNullError) # # report to your bug tracker here # return nil # end super end # Union and Interface Resolution def self.resolve_type(abstract_type, obj, ctx) # TODO: Implement this method # to return the correct GraphQL object type for `obj` raise(GraphQL::RequiredImplementationMissingError) end # Relay-style Object Identification: # Return a string UUID for `object` def self.id_from_object(object, type_definition, query_ctx) # For example, use Rails' GlobalID library (https://github.com/rails/globalid): object_id = object.to_global_id.to_s # Remove this redundant prefix to make IDs shorter: object_id = object_id.sub("gid://#{GlobalID.app}/", "") encoded_id = Base64.urlsafe_encode64(object_id) # Remove the "=" padding encoded_id = encoded_id.sub(/=+/, "") # Add a type hint type_hint = type_definition.graphql_name.first "#{type_hint}_#{encoded_id}" end # Given a string UUID, find the object def self.object_from_id(encoded_id_with_hint, query_ctx) # For example, use Rails' GlobalID library (https://github.com/rails/globalid): # Split off the type hint _type_hint, encoded_id = encoded_id_with_hint.split("_", 2) # Decode the ID id = Base64.urlsafe_decode64(encoded_id) # Rebuild it for Rails then find the object: full_global_id = "gid://#{GlobalID.app}/#{id}" GlobalID::Locator.locate(full_global_id) end end
zhaozixiao/rubyMe
todoItems/app/graphql/types/mutation_type.rb
module Types class MutationType < Types::BaseObject field :create_todo, mutation: Mutations::CreateTodo field :update_todo, mutation: Mutations::UpdateTodo field :create_user, mutation: Mutations::CreateUser field :signin_user, mutation: Mutations::SignInUser end end
zhaozixiao/rubyMe
todoItems/app/graphql/mutations/update_todo.rb
<reponame>zhaozixiao/rubyMe<gh_stars>0 require 'time' module Mutations class UpdateTodo < BaseMutation # arguments passed to the `resolve` method argument :user, String, required: true argument :id, ID, required: true argument :description, String, required: false argument :status, String, required: false validates required: { one_of: [:description, :status] } # return type from the mutation type Types::TodoType def resolve(**inputs) todo = Todo.find_by!(id: inputs[:id]) if inputs[:description] != nil todo.update!(description: inputs[:description], updated_by: inputs[:user], updated_at: Time.now()) elsif inputs[:status] != nil todo.update!(status: inputs[:status], updated_by: inputs[:user], updated_at: Time.now()) end return todo end end end
zhaozixiao/rubyMe
todoItems/db/migrate/20211213064402_add_status_to_todos.rb
<reponame>zhaozixiao/rubyMe class AddStatusToTodos < ActiveRecord::Migration[6.1] def change execute <<-SQL CREATE TYPE todo_status AS ENUM ('ACTIVE', 'COMPLETE', 'DELETED'); SQL add_column :todos, :status, :todo_status, null: false, default: "ACTIVE" end end
zhaozixiao/rubyMe
todoItems/app/graphql/types/query_type.rb
<reponame>zhaozixiao/rubyMe<gh_stars>0 module Types class QueryType < Types::BaseObject # Add `node(id: ID!) and `nodes(ids: [ID!]!)` include GraphQL::Types::Relay::HasNodeField include GraphQL::Types::Relay::HasNodesField # Add root-level fields here. # They will be entry points for queries on your schema. field :all_todos, [TodoType], null: false def all_todos Todo.order(created_at: :desc).all end end end
zhaozixiao/rubyMe
todoItems/app/graphql/mutations/create_todo.rb
module Mutations class CreateTodo < BaseMutation # arguments passed to the `resolve` method argument :description, String, required: true argument :reference, String, required: true # return type from the mutation type Types::TodoType def resolve(description: nil, reference: nil) Todo.create!( description: description, reference: reference, ) end end end
zhaozixiao/rubyMe
todoItems/db/migrate/20211213071401_add_meta_data_to_todos.rb
class AddMetaDataToTodos < ActiveRecord::Migration[6.1] def change add_column :todos, :created_by, :string add_column :todos, :updated_by, :string add_column :todos, :deleted_at, :timestamp add_column :todos, :deleted_by, :string end end
zhaozixiao/rubyMe
todoItems/app/graphql/types/todo_type.rb
<gh_stars>0 module Types class TodoType < Types::BaseObject field :id, ID, null: false field :description, String, null: false field :reference, String, null: false field :status, String, null: false end end
zhaozixiao/rubyMe
todoItems/app/models/todo.rb
<reponame>zhaozixiao/rubyMe<filename>todoItems/app/models/todo.rb class Todo < ApplicationRecord enum status: { active: "ACTIVE", complete: "COMPLETE", deleted: "DELETED" } end
shem8/jekyll-seo-script
jekyll-seo.rb
<gh_stars>10-100 #!/usr/bin/env ruby # Purpose: A simple script to identify SEO problems in jekyll blog posts # License: http://github.com/bhardin/jekyll-seo/license.txt require 'optparse' require 'nokogiri' heading = []; title = []; url = []; content = []; meta_description = []; temp = []; options = {} optparse = OptionParser.new do|opts| # Set a banner, displayed at the top of the help screen. opts.banner = "Usage: ./jekyll-seo -k keywords FILE" # Define the options, and what they do options[:verbose] = false opts.on( '-v', '--verbose', 'Output more information' ) do options[:verbose] = true end options[:keyword] = nil opts.on( '-k', '--keyword KEYWORD', 'keyword your post should be optimized for' ) do|keyword| options[:keyword] = keyword end options[:post] = nil opts.on( '-p', '--post FILE', 'post to be analyzed' ) do|post| options[:post] = post end opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end end optparse.parse! puts "Being verbose" if options[:verbose] if options[:verbose] puts "keyword: #{options[:keyword]}" if options[:keyword] #puts "analyzing post: #{options[:post]}" if options[:post] end if options[:post] f = options[:post] puts "Analyzing Post: #{f}..." post = Nokogiri::HTML(open(f)) # Search for keyword in heading post.css('h1').each do |this| if options[:verbose] puts "heading found" puts "heading: #{this}" end heading = this.to_s.scan(/#{options[:keyword]}/i) if options[:verbose] puts "heading-found: #{title}" end end # Search for keyword in title post.css('title').each do |this| if options[:verbose] puts "title found" puts "title: #{this}" end title = this.to_s.scan(/#{options[:keyword]}/i) if options[:verbose] puts "title-found: #{title}" end end # Search for keyword in body post.css('body').each do |this| if options[:verbose] puts "content found" #puts "content: #{this}" end content = this.to_s.scan(/#{options[:keyword]}/i) end # Search for keyword in Meta Description post.css('meta').each do |this| if this.attribute("name").to_s == "description" if options[:verbose] puts "Meta Description found" puts "Meta Description: #{this.attribute('content')}" end meta_description = this.attribute("content").to_s.scan(/#{options[:keyword]}/i) end end puts "" puts "Article Heading: #{not heading.empty?} (#{heading.count})" puts "Page title: #{not title.empty?} (#{title.count})" # puts "Page URL: Yes (1)" puts "Content: #{not content.empty?} (#{content.count})" puts "Meta description: #{not meta_description.empty?} (#{meta_description.count})" else puts "No post given to analyze. Try with -h" end #You have not used your keyword / keyphrase in any subheading (such as an H2) in your copy. #No images appear in this page, consider adding some as appropriate. #The meta description is under 120 characters, however up to 156 characters are available. The available space is shorter than the usual 155 characters because Google will also include the publication date in the snippet. #The page title contains keyword / phrase, but it does not appear at the beginning; try and move it to the beginning. #The keyword / phrase does not appear in the URL for this page. If you decide to rename the URL be sure to check the old URL 301 redirects to the new one! #The copy scores 68.9 in the Flesch Reading Ease test, which is considered OK to read. #This page has 14 outbound link(s). #The keyword density is 1.74%, which is great, the keyword was found 15 times. #The meta description contains the primary keyword / phrase. #There are 890 words contained in the body copy, this is greater than the 300 word recommended minimum. #The page title is more than 40 characters and less than the recommended 70 character limit. #The keyword appears in the first paragraph of the copy.
unindented/unindented-rails
spec/lib/kramdown_processor_spec.rb
describe KramdownProcessor do subject do KramdownProcessor.new(enable_coderay: false) end describe '#process' do it 'converts a bunch of Markdown to HTML' do body = Capybara.string(subject.process(<<-eos # Foo eos )) expect(body).to have_xpath('//h1') end it 'recognizes blocks fenced with ```' do body = Capybara.string(subject.process(<<-eos ```sh echo 'Foo!' ``` eos )) expect(body).to have_xpath('//pre') end end end
unindented/unindented-rails
lib/kramdown_processor.rb
<reponame>unindented/unindented-rails<gh_stars>0 require 'kramdown' class KramdownProcessor DEFAULT_OPTS = { } def initialize(opts = {}) @opts = DEFAULT_OPTS.merge(opts) end def process(str) convert_to_html(fix_fenced_blocks(str)) end private def fix_fenced_blocks(str) str.gsub(/^```/, '~~~') end def convert_to_html(str) ::Kramdown::Document.new(str, @opts).to_html end end
unindented/unindented-rails
spec/decorators/tags_decorator_spec.rb
describe TagsDecorator do describe '#cloud_list' do it 'generates a tag cloud' do tags = FactoryGirl.create_list(:tag, 2) contents = FactoryGirl.create_list(:content, 2) contents.each_with_index do |content, index| content.tags << tags[index % tags.length] end cloud = Tag.counts.decorate list = Capybara.string(cloud.cloud_list) expect(list).to have_xpath("//li/a[@rel='tag']", count: tags.length) end end end
unindented/unindented-rails
db/migrate/20131201000001_create_contents.rb
<filename>db/migrate/20131201000001_create_contents.rb class CreateContents < ActiveRecord::Migration def change create_table :contents do |t| t.string :title, null: false t.string :author t.boolean :published, null: false, default: true t.boolean :featured, null: false, default: false t.string :abstract t.string :abstract_html t.text :body, null: false t.text :body_html, null: false t.string :path, null: false, index: true t.string :locator, null: false, index: true t.string :category, null: false, index: true t.date :date end end end
unindented/unindented-rails
app/controllers/feeds_controller.rb
class FeedsController < ApplicationController respond_to :atom, :tile def show @contents = Content .categorized([:articles, :experiments]) .includes(:tags) .limit(6) .decorate respond_with @contents end end
unindented/unindented-rails
spec/models/extension_spec.rb
describe Extension do describe '#valid?' do it 'fails with no name' do expect(FactoryGirl.build(:extension, name: nil)).to have(1).error_on(:name) end it 'fails with duplicate name' do extension = FactoryGirl.create(:extension) expect(FactoryGirl.build(:extension, name: extension.name)).to have(1).error_on(:name) end end describe '#locator' do it 'gets generated based on the name' do extension = FactoryGirl.create(:extension, name: 'FooBar') expect(extension.locator).to eq('foobar') end end describe '#to_param' do it 'returns the locator' do extension = FactoryGirl.create(:extension, name: 'FooBar') expect(extension.to_param).to eq('foobar') end end end
unindented/unindented-rails
app/models/content_tag.rb
class ContentTag < ActiveRecord::Base belongs_to :content belongs_to :tag end
unindented/unindented-rails
features/support/env.rb
require 'simplecov' require 'cucumber/rails' require 'rspec/expectations' ActionController::Base.allow_rescue = false DatabaseCleaner.strategy = :transaction Cucumber::Rails::Database.javascript_strategy = :truncation Capybara.javascript_driver = :poltergeist
unindented/unindented-rails
spec/routing/articles_routing_spec.rb
describe ArticlesController do describe 'routing' do it 'routes `/articles` to #show' do expect(get '/articles/').to route_to('articles#show') end it 'routes `/articles/2013` to #show' do expect(get '/articles/2013/').to route_to( 'articles#show', year: '2013') end it 'routes `/articles/2013/02` to #show' do expect(get '/articles/2013/02/').to route_to( 'articles#show', year: '2013', month: '02') end it 'routes `/articles/2013/02/01` to #show' do expect(get '/articles/2013/02/01/').to route_to( 'articles#show', year: '2013', month: '02', day: '01') end end describe 'named routes' do it 'routes `articles_path` to #show' do expect(get articles_path).to route_to('articles#show') end it 'routes `/articles/2013` to #show' do expect(get archive_articles_path(year: '2013')).to route_to( 'articles#show', year: '2013') end it 'routes `/articles/2013/02` to #show' do expect(get archive_articles_path(year: '2013', month: '02')).to route_to( 'articles#show', year: '2013', month: '02') end it 'routes `/articles/2013/02/01` to #show' do expect(get archive_articles_path(year: '2013', month: '02', day: '01')).to route_to( 'articles#show', year: '2013', month: '02', day: '01') end end end
unindented/unindented-rails
lib/tasks/build.rake
require 'open3' namespace :build do desc 'Generate a mirror of the site' task :mirror => :environment do env = Rails.env port = SETTINGS.build.port rails_cmd = "RAILS_ENV=#{env} rails server --port #{port}" rm_cmd = "rm -rf build/localhost:#{port}/" wget_cmd = "wget --content-on-error --mirror --directory-prefix=build localhost:#{port}" cp_cmd = "cp -r public/ build/localhost:#{port}/" puts "Starting up server..." Open3.popen2e(rails_cmd) do |rails_in, rails_oe, rails_wait| rails_oe.each do |line| if line.include?('WEBrick::HTTPServer#start:') Thread.new do puts "Cleaning up build folder..." puts %x(#{rm_cmd}) puts "Mirroring site..." puts %x(#{wget_cmd}) puts "Killing server..." Process.kill('TERM', rails_wait.pid) end end end end puts "Copying misc files..." puts %x(#{cp_cmd}) end desc 'Deploy the site to the destination' task :deploy => :environment do port = SETTINGS.build.port src = "./build/localhost:#{port}/" dst = SETTINGS.build.destination rsync_cmd = "rsync --archive --compress --delete --verbose #{src} #{dst}" puts "Deploying from #{src} to #{dst}..." puts %x(#{rsync_cmd}) end end desc 'Build and deploy the site' task :build => ['contents:reset', 'build:mirror', 'build:deploy']
unindented/unindented-rails
app/models/extension.rb
<reponame>unindented/unindented-rails class Extension < ActiveRecord::Base default_scope { order(:name) } has_many :content_extensions has_many :contents, through: :content_extensions validates :name, presence: true, uniqueness: true before_save :update_locator def to_param self.locator end private def update_locator self.locator = self.name.parameterize end end
unindented/unindented-rails
lib/tasks/contents.rake
require 'content_loader' namespace :contents do desc 'Load all contents into the database' task :load => :environment do src = Rails.root.join('contents').to_s ContentLoader.new.load(src) end desc 'Reset the contents of the database' task :reset => ['db:migrate', 'db:reset', 'contents:load'] end desc 'Alias for contents:reset' task :contents => 'contents:reset'
unindented/unindented-rails
app/views/feeds/show.tile.builder
tile_feed do |feed| feed.binding(template: 'TileSquare150x150Text04', fallback: 'TileSquareImage') do content = @contents.first feed.text(content.title, id: '1') end if @contents.length > 0 feed.binding(template: 'TileWide310x150Text09', fallback: 'TileWideImage') do content = @contents.first feed.text(content.title, id: '1') feed.text(content.abstract, id: '2') end if @contents.length > 0 feed.binding(template: 'TileSquare310x310TextList03', contentId: @contents.first.id) do @contents.first(3).each_with_index do |content, index| feed.text(content.title, id: "#{2 * index + 1}") feed.text(content.abstract, id: "#{2 * index + 2}") end end if @contents.length > 0 end
unindented/unindented-rails
config/locales/en.rb
<filename>config/locales/en.rb { en: { date: { formats: { year: "%Y", month: "%B, %Y", day: lambda { |date, _| "%B #{date.day.ordinalize}, %Y" } } } } }
unindented/unindented-rails
spec/factories/extensions.rb
FactoryGirl.define do sequence :extension_name do |n| "extension#{n}" end factory(:extension) do name { FactoryGirl.generate(:extension_name) } end end
unindented/unindented-rails
config/environments/development.rb
<reponame>unindented/unindented-rails Rails.application.configure do config.cache_classes = false config.eager_load = false config.assets.debug = false config.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_controller.default_url_options = { trailing_slash: true } config.active_support.deprecation = :log config.active_record.migration_error = :page_load end
unindented/unindented-rails
db/migrate/20131201000002_create_tags.rb
<filename>db/migrate/20131201000002_create_tags.rb class CreateTags < ActiveRecord::Migration def change create_table :tags do |t| t.string :name, null: false t.string :locator, null: false, index: true end end end
unindented/unindented-rails
config/initializers/i18n.rb
module I18n class JustRaiseExceptionHandler < ExceptionHandler def call(exception, locale, key, options) if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule' raise exception.to_exception else super end end end end I18n.exception_handler = I18n::JustRaiseExceptionHandler.new
unindented/unindented-rails
app/models/content_extension.rb
<filename>app/models/content_extension.rb class ContentExtension < ActiveRecord::Base belongs_to :content belongs_to :extension end
unindented/unindented-rails
app/controllers/archives_controller.rb
class ArchivesController < ApplicationController respond_to :html def show category = controller_name info = params.slice(:year, :month, :day).merge(category: category) page = params[:page] @date = PartialDate.new(info) .decorate @contents = Content .categorized(category) .between(@date.to_range) .page(page) .decorate respond_with @contents, layout: "#{category}_archive" end end
unindented/unindented-rails
config/routes.rb
Rails.application.routes.draw do archive_constraint = { year: /\d{4}/, month: /\d{2}/, day: /\d{2}/, page: /\d+/ } filename_constraint = { filename: /.+\.[a-z]+/ } root to: 'home#show' resource :feed, only: [:show] resource :articles, only: [:show], format: false do get '(:year(/:month(/:day)))(/page/:page)', action: :show, constraints: archive_constraint, as: :archive end resource :experiments, only: [:show], format: false do get '(:year(/:month(/:day)))(/page/:page)', action: :show, constraints: archive_constraint, as: :archive end resources :tags, only: [:index, :show], param: :locator, format: false do get 'page/:page', action: :show, on: :member, as: :archive end resources :errors, only: [:show], param: :error, format: false get '*locator/:filename', to: 'contents#show', format: false, constraints: filename_constraint, as: :file_content get '*locator', to: 'contents#show', format: false, as: :content end
unindented/unindented-rails
spec/factories/partial_dates.rb
FactoryGirl.define do factory(:partial_date) do ignore do date { Date.today - Random.rand(3333) } end category { %w{articles experiments}[Random.rand(2)] } year { date.year } end end
unindented/unindented-rails
spec/decorators/contents_decorator_spec.rb
<gh_stars>0 describe ContentsDecorator do let!(:contents) { FactoryGirl.create_list(:content, 3) } describe '#title' do it 'returns the title of the site' do feed = Content.all.decorate expect(feed.title).to eq(helpers.title_text) end end describe '#author' do it 'returns the subtitle of the site' do feed = Content.all.decorate expect(feed.subtitle).to eq(helpers.subtitle_text) end end describe '#updated' do it 'returns the date of the most recent content' do feed = Content.all.decorate expect(feed.updated).to eq(feed.first.datetime) end end describe '#author' do it 'returns the author of the site' do feed = Content.all.decorate expect(feed.author).to eq(helpers.author_text) end end describe '#copyright' do it 'returns the copyright of the site' do feed = Content.all.decorate expect(feed.copyright).to eq(helpers.copyright_text) end end end
unindented/unindented-rails
app/models/partial_date.rb
<reponame>unindented/unindented-rails<filename>app/models/partial_date.rb class PartialDate include ActiveAttr::Model attribute :category, type: String attribute :year, type: Integer attribute :month, type: Integer attribute :day, type: Integer validates :category, :year, presence: true def to_a return nil unless valid? [year, month, day].compact end def to_range return nil unless valid? array = to_a msg = [:end_of_year, :end_of_month, :end_of_day][array.length - 1] min = Date.new(*array) max = min.clone.send(msg) min..max end def decorate PartialDateDecorator.decorate(self) end end
unindented/unindented-rails
lib/content_loader.rb
class ContentLoader def load(folder) Dir.chdir(Rails.root.join(folder)) do Dir.glob('**/index.metadata') do |filename| Content.create!(extract_data(filename)) end end end private def extract_data(filename) [ :extract_data_from_filename!, :extract_data_from_yaml!, :extract_data_from_markdown!, :generate_locator!, :generate_tags_list!, :generate_extensions_list!, ].reduce({}) { |data, method| self.send(method, data, filename) } end def extract_data_from_filename!(data, filename) match = regex.match(filename) captures = Hash[match.names.zip(match.captures)] data.merge!(captures) end def extract_data_from_yaml!(data, filename) data.merge!(YAML.load_file(filename)) end def extract_data_from_markdown!(data, filename) data.merge!({ 'body' => read_body(filename) }) end def generate_locator!(data, filename) slug = data.delete('slug') rest = data.delete('rest') data['locator'] = File.join(data['category'], slug || rest).chomp('/') data end def generate_tags_list!(data, filename) data['tags_list'] = data.delete('tags') data end def generate_extensions_list!(data, filename) data['extensions_list'] = data.delete('extensions') data end def read_body(filename) path = "#{File.dirname(filename)}/#{File.basename(filename, '.*')}.md" File.read(path) if File.file?(path) end def regex @regex ||= /\A (?<path> (?<category>[^\/]+) ( \/ (?<date>\d{4}-\d{2}-\d{2})-(?<slug>[^\/]+) | (?<rest>.*?) )? \/ ) index.metadata \z/x end end
unindented/unindented-rails
config/environments/production.rb
Rails.application.configure do config.cache_classes = true config.eager_load = true config.serve_static_assets = true config.static_cache_control = "public, max-age=#{1.year.to_i}" config.assets.js_compressor = :uglifier config.assets.css_compressor = :sass config.assets.compile = true config.assets.digest = true config.assets.version = '1.0' config.consider_all_requests_local = false config.action_controller.perform_caching = true config.action_controller.default_url_options = { trailing_slash: true } config.active_support.deprecation = :notify config.i18n.fallbacks = true config.log_level = :info config.log_formatter = ::Logger::Formatter.new end
unindented/unindented-rails
app/models/concerns/processable.rb
module Processable extend ActiveSupport::Concern included do processor = BodyProcessor.new({ kramdown: SETTINGS.processors.kramdown_as_a_hash.deep_symbolize_keys, nokogiri: SETTINGS.processors.nokogiri_as_a_hash.deep_symbolize_keys, pygments: SETTINGS.processors.pygments_as_a_hash.deep_symbolize_keys }) define_method(:process) { |body| processor.process(body) } end end
unindented/unindented-rails
app/helpers/application_helper.rb
module ApplicationHelper extend TextHelper extend LinkHelper extend MetaHelper extend MicrosoftHelper extend TwitterHelper extend ScriptHelper end
unindented/unindented-rails
app/decorators/tags_decorator.rb
<filename>app/decorators/tags_decorator.rb class TagsDecorator < CollectionDecorator delegate :current_page, :total_pages, :limit_value def cloud_list(classes = %w{s m l}) return if length == 0 max = max_by(&:count) items = reduce('') do |memo, tag| index = ((classes.size - 1.0) * tag.count / max.count).round link = link_to(tag.name, tag_path(tag), class: :tag, rel: :tag) item = content_tag(:li, link, class: classes[index]) memo + item end content_tag(:ul, items.html_safe, class: [:cloud, :container]) end end
unindented/unindented-rails
app/controllers/tags_controller.rb
<gh_stars>0 class TagsController < ApplicationController respond_to :html def index @tags = Tag .counts .decorate respond_with @tags, layout: 'tags' end def show locator = params[:locator] page = params[:page] @tag = Tag .find_by!(locator: locator) .decorate @contents = @tag.contents .page(page) .decorate respond_with @contents, layout: 'tags' end end
unindented/unindented-rails
spec/controllers/feeds_controller_spec.rb
<gh_stars>0 describe FeedsController do describe 'GET show :atom' do context 'without contents' do it 'has a 200 status code' do get :show, format: :atom expect(response.status).to eq(200) end end context 'with contents' do let!(:contents) { FactoryGirl.create_list(:content, 2) } it 'has a 200 status code' do get :show, format: :atom expect(response.status).to eq(200) end end end describe 'GET show :tile' do context 'without contents' do it 'has a 200 status code' do get :show, format: :tile expect(response.status).to eq(200) end end context 'with contents' do let!(:contents) { FactoryGirl.create_list(:content, 2) } it 'has a 200 status code' do get :show, format: :tile expect(response.status).to eq(200) end end end end
unindented/unindented-rails
app/controllers/articles_controller.rb
<reponame>unindented/unindented-rails<filename>app/controllers/articles_controller.rb class ArticlesController < ArchivesController end
unindented/unindented-rails
app/models/tag.rb
class Tag < ActiveRecord::Base default_scope { order(:name) } has_many :content_tags has_many :contents, through: :content_tags validates :name, presence: true, uniqueness: true before_save :update_locator def self.counts select(['tags.*', 'count(content_tags.tag_id) as count']) .joins(:content_tags) .group('content_tags.tag_id') end def to_param self.locator end private def update_locator self.locator = self.name.parameterize end end
unindented/unindented-rails
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery rescue_from ActiveRecord::RecordNotFound, with: :render_404 rescue_from Errno::ENOENT, with: :render_404 def render_404 respond_to do |format| format.html { render 'errors/404', layout: 'errors', status: :not_found } format.any { head :not_found } end end end
unindented/unindented-rails
app/helpers/text_helper.rb
<filename>app/helpers/text_helper.rb module TextHelper def host_text SETTINGS.host end def website_text SETTINGS.website end def author_text SETTINGS.author end def email_text SETTINGS.email end def twitter_text SETTINGS.twitter end def github_text SETTINGS.github end def title_text t(:title, website: website_text) end def subtitle_text t(:subtitle, author: author_text) end def copyright_text t('shared.page_meta.copyright', author: author_text, license: t('shared.page_meta.license') ) end end
unindented/unindented-rails
spec/lib/body_processor_spec.rb
describe BodyProcessor do subject do BodyProcessor.new( kramdown: { enable_coderay: false }, nokogiri: { css: 'table' }, pygments: { misc: { cssclass: 'highlighted' } } ) end describe '#process' do it 'processes the body of a content' do body = Capybara.string(subject.process(<<-eos # Foo | Bar | Baz | ```sh echo 'Qux!' ``` eos )) expect(body).to have_xpath('//div[@class="overflow"]/table') expect(body).to have_xpath('//div[@class="highlighted"]/pre') end it 'does not output a full HTML document' do body = subject.process(<<-eos # Foo eos ) expect(body).not_to include('DOCTYPE') end end end
unindented/unindented-rails
config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store, key: '_website_session'
unindented/unindented-rails
spec/routing/home_routing_spec.rb
describe HomeController do describe 'routing' do it 'routes `/` to #show' do expect(get '/').to route_to('home#show') end end describe 'named routes' do it 'routes `root_path` to #show' do expect(get root_path).to route_to('home#show') end end end
unindented/unindented-rails
db/schema.rb
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20131201000005) do create_table "content_extensions", force: true do |t| t.integer "content_id", null: false t.integer "extension_id", null: false end add_index "content_extensions", ["content_id"], name: "index_content_extensions_on_content_id" add_index "content_extensions", ["extension_id"], name: "index_content_extensions_on_extension_id" create_table "content_tags", force: true do |t| t.integer "content_id", null: false t.integer "tag_id", null: false end add_index "content_tags", ["content_id"], name: "index_content_tags_on_content_id" add_index "content_tags", ["tag_id"], name: "index_content_tags_on_tag_id" create_table "contents", force: true do |t| t.string "title", null: false t.string "author" t.boolean "published", default: true, null: false t.boolean "featured", default: false, null: false t.string "abstract" t.string "abstract_html" t.text "body", null: false t.text "body_html", null: false t.string "path", null: false t.string "locator", null: false t.string "category", null: false t.date "date" end create_table "extensions", force: true do |t| t.string "name", null: false t.string "locator", null: false end create_table "tags", force: true do |t| t.string "name", null: false t.string "locator", null: false end end
unindented/unindented-rails
app/models/concerns/taggable.rb
<reponame>unindented/unindented-rails<filename>app/models/concerns/taggable.rb module Taggable extend ActiveSupport::Concern included do has_many :content_tags has_many :tags, through: :content_tags end def tags_list self.tags.map(&:name) end def tags_list=(names) self.tags = (names || []).map { |name| Tag.find_or_create_by!(name: name) } end end
unindented/unindented-rails
app/helpers/link_helper.rb
<reponame>unindented/unindented-rails module LinkHelper def email_link(text = email_text, opts = {}) link_to(text, email_url(email_text, opts)) end def github_link(text = "@#{github_text}", opts = {}) link_to(text, github_url(github_text, opts)) end def twitter_link(text = "@#{twitter_text}", opts = {}) link_to(text, twitter_url(twitter_text, opts)) end def tweet_link(text = "@#{twitter_text}", opts = {}) link_to(text, tweet_url(opts)) end end
unindented/unindented-rails
spec/decorators/partial_date_decorator_spec.rb
<reponame>unindented/unindented-rails<gh_stars>0 describe PartialDateDecorator do describe '#localize' do it 'returns a year' do date = FactoryGirl.build(:partial_date, year: 2013).decorate expect(date.localize).to eq('2013') end it 'returns a year and a month' do date = FactoryGirl.build(:partial_date, year: 2013, month: 2).decorate expect(date.localize).to eq('February, 2013') end it 'returns a year, a month and a day' do date = FactoryGirl.build(:partial_date, year: 2013, month: 2, day: 1).decorate expect(date.localize).to eq('February 1st, 2013') end end describe '#route' do it 'generates the route for a year' do date = FactoryGirl.build(:partial_date, category: :articles, year: 2013).decorate expect(date.route).to eq(helpers.archive_articles_path(year: '2013')) end it 'generates the route for a year and a month' do date = FactoryGirl.build(:partial_date, category: :articles, year: 2013, month: 2).decorate expect(date.route).to eq(helpers.archive_articles_path(year: '2013', month: '02')) end it 'generates the route for a year, a month and a day' do date = FactoryGirl.build(:partial_date, category: :articles, year: 2013, month: 2, day: 1).decorate expect(date.route).to eq(helpers.archive_articles_path(year: '2013', month: '02', day: '01')) end end describe '#parent_route' do it 'generates the parent route for a year' do date = FactoryGirl.build(:partial_date, category: :articles, year: 2013).decorate expect(date.parent_route).to eq(helpers.archive_articles_path) end it 'generates the parent route for a year and a month' do date = FactoryGirl.build(:partial_date, category: :articles, year: 2013, month: 2).decorate expect(date.parent_route).to eq(helpers.archive_articles_path(year: '2013')) end it 'generates the parent route for a year, a month and a day' do date = FactoryGirl.build(:partial_date, category: :articles, year: 2013, month: 2, day: 1).decorate expect(date.parent_route).to eq(helpers.archive_articles_path(year: '2013', month: '02')) end end end
unindented/unindented-rails
lib/icon_generator.rb
<gh_stars>0 class IconGenerator def ico(png, options = {}) options[:sizes].each do |name, size| ico = yield(name, options) convert_with_image_magick(png, ico, size) end end def png(svg, options = {}) options[:sizes].each do |name, size| png = yield(name, options) convert_with_inkscape(svg, png, size) end end private def convert_with_image_magick(png, ico, size) options = "" if size.kind_of?(Array) options += size.reduce('') { |memo, size| "#{memo} \\( -clone 0 -resize #{size} \\)" } options += " -delete 0" else options += " -resize #{size}" end puts %x{convert #{png} #{options} #{ico}} end def convert_with_inkscape(svg, png, size) options = "--without-gui --export-width #{size} --export-height #{size}" puts %x{inkscape #{options} --export-png #{png} #{svg}} end end
unindented/unindented-rails
config/initializers/mime_types.rb
<reponame>unindented/unindented-rails Mime::Type.register('image/svg+xml', :svg) unless Mime::Type.lookup_by_extension(:svg)
unindented/unindented-rails
features/step_definitions/common_steps.rb
Transform /^(\d+)$/ do |number| number.to_i end Transform(/^table:.+$/) do |table| table.map_headers! do |header| header.underscore.to_sym end table.map_column!(:tags, false) do |tags| tags.split(/\s*,\s*/).map do |tag_name| Tag.find_or_create_by!(name: tag_name) end end table.map_column!(:extensions, false) do |extensions| extensions.split(/\s*,\s*/).map do |ext_name| Extension.find_or_create_by!(name: ext_name) end end table end Given(/^the (about) page exists$/) do |locator| FactoryGirl.create(:content, locator: locator) end Given(/^the following contents exist:$/) do |contents| contents.hashes.each do |content| FactoryGirl.create(:content, content) end end Given(/^the following (articles|experiments) exist:$/) do |category, contents| contents.hashes.each do |content| FactoryGirl.create(:content, content.merge(category: category)) end end Given(/^that (\d+) (articles|experiments) exist$/) do |number, category| FactoryGirl.create_list(:content, number, category: category) end When(/^I visit "([^"]+)"$/) do |route| visit route end When(/^I click on "([^"]+)"$/) do |text| find_link(text).click end When(/^I trigger "([^"]+)" on "([^"]+)"$/) do |event, text| find_link(text).trigger(event) end Then(/^I should (not )?see the title "([^"]+)"$/) do |negate, text| method = negate.present? ? 'to_not' : 'to' expect(page).send(method, have_title(text)) end Then(/^I should (not )?see the header "([^"]+)"$/) do |negate, text| method = negate.present? ? 'to_not' : 'to' expect(page).send(method, have_selector('h1', text: text)) end Then(/^I should (not )?see the link "([^"]+)"(?: pointing to "([^"]+)")?$/) do |negate, text, href| method = negate.present? ? 'to_not' : 'to' opts = { href: href } if href.present? expect(page).send(method, have_link(text, opts)) end Then(/^I should (not )?see the text "([^"]*)"$/) do |negate, text| method = negate.present? ? 'to_not' : 'to' expect(page).send(method, have_text(text)) end Then(/^I should (not )?see "([^"]*)" before "([^"]*)"$/) do |negate, text1, text2| method = negate.present? ? 'to_not' : 'to' expect(page).send(method, have_before(text1, text2)) end Then(/^I should (not )?see the tag "([^"]*)"(?: with the value "([^"]*)")?$/) do |negate, xpath, value| method = negate.present? ? 'to_not' : 'to' expect(page).send(method, have_xpath("//#{xpath}", text: value)) end Then(/^I should (not )?see the (?:head|script) tag "([^"]*)"(?: with the value "([^"]*)")?$/) do |negate, xpath, value| method = negate.present? ? 'to_not' : 'to' expect(page).send(method, have_xpath("//#{xpath}", text: value, visible: false)) end
unindented/unindented-rails
spec/models/partial_date_spec.rb
describe PartialDate do describe '#valid?' do it 'fails with no category' do expect(FactoryGirl.build(:partial_date, category: nil)).to have(1).error_on(:category) end it 'fails with no year' do expect(FactoryGirl.build(:partial_date, year: nil)).to have(1).error_on(:year) end end describe '#to_a' do it 'returns nil if the date is not valid' do date = FactoryGirl.build(:partial_date, category: nil) expect(date.to_a).to be_nil end it 'returns an array with the year' do date = FactoryGirl.build(:partial_date, year: 2013) expect(date.to_a).to eq([2013]) end it 'returns an array with the year and month' do date = FactoryGirl.build(:partial_date, year: 2013, month: 2) expect(date.to_a).to eq([2013, 2]) end it 'returns an array with the year, month and day' do date = FactoryGirl.build(:partial_date, year: 2013, month: 2, day: 1) expect(date.to_a).to eq([2013, 2, 1]) end end describe '#to_range' do it 'returns nil if the date is not valid' do date = FactoryGirl.build(:partial_date, category: nil) expect(date.to_a).to be_nil end it 'returns a range with the year' do date = FactoryGirl.build(:partial_date, year: 2013) expect(date.to_range).to cover(Date.new(2013), Date.new(2014) - 1) expect(date.to_range).to_not cover(Date.new(2014)) end it 'returns a range with the year and month' do date = FactoryGirl.build(:partial_date, year: 2013, month: 2) expect(date.to_range).to cover(Date.new(2013, 2), Date.new(2013, 3) - 1) expect(date.to_range).to_not cover(Date.new(2013, 3)) end it 'returns a range with the year, month and day' do date = FactoryGirl.build(:partial_date, year: 2013, month: 2, day: 1) expect(date.to_range).to cover(Date.new(2013, 2, 1)) expect(date.to_range).to_not cover(Date.new(2013, 1, 31), Date.new(2013, 2, 2)) end end end
unindented/unindented-rails
app/decorators/partial_date_decorator.rb
<gh_stars>0 class PartialDateDecorator < ModelDecorator delegate_all def localize array = to_a format = [:year, :month, :day][array.length - 1] l(Date.new(*array), format: format) end def route convert_to_route(to_a) end def parent_route convert_to_route(to_a[0...-1]) end private def convert_to_route(array) array = array.map { |v| v.to_s.rjust(2, '0') } send("archive_#{category}_path", Hash[[:year, :month, :day].zip(array)]) end end
unindented/unindented-rails
spec/helpers/url_helper_spec.rb
<gh_stars>0 describe UrlHelper do describe '#absolute_url' do before { allow(SETTINGS).to receive(:host) { 'http://www.foo.com' } } it 'returns the absolute URL for the specified path' do url = helper.absolute_url('/bar') expect(url).to eq('http://www.foo.com/bar') end end describe '#current_url' do before do allow(SETTINGS).to receive(:host) { 'http://www.foo.com' } allow(controller.request).to receive(:original_fullpath).and_return('/bar') end it 'returns the absolute current URL' do url = helper.current_url expect(url).to eq('http://www.foo.com/bar') end end describe '#email_url' do before { allow(SETTINGS).to receive(:email) { '<EMAIL>' } } context 'without options' do it 'returns the URL to the configured email address' do url = helper.email_url expect(url).to eq('mailto:<EMAIL>') end end context 'with an email address' do it 'returns the URL to the specified email address' do url = helper.email_url('<EMAIL>') expect(url).to eq('mailto:<EMAIL>') end end context 'with a subject' do it 'returns the URL with the specified subject as a param' do url = helper.email_url('<EMAIL>', subject: 'Baz') expect(url).to eq('mailto:<EMAIL>?subject=Baz') end end end describe '#github_url' do before { allow(SETTINGS).to receive(:github) { 'foobar' } } context 'without options' do it 'returns the URL to the configured GitHub account' do url = helper.github_url expect(url).to eq('https://github.com/foobar') end end context 'with a handle' do it 'returns the URL to the specified GitHub account' do url = helper.github_url('foobaz') expect(url).to eq('https://github.com/foobaz') end end end describe '#twitter_url' do before { allow(SETTINGS).to receive(:twitter) { 'foobar' } } context 'without options' do it 'returns the URL to the specified Twitter account' do url = helper.twitter_url expect(url).to eq('https://twitter.com/foobar') end end context 'with a handle' do it 'returns the URL to the specified Twitter account' do url = helper.twitter_url('foobaz') expect(url).to eq('https://twitter.com/foobaz') end end end describe '#tweet_url' do context 'without options' do it 'returns the URL for the `tweet` intent' do url = helper.tweet_url expect(url).to eq('https://twitter.com/intent/tweet') end end context 'with a URL' do it 'returns the URL with the specified URL encoded as a param' do url = helper.tweet_url(url: 'http://foobar.com/') expect(url).to eq('https://twitter.com/intent/tweet?url=http%3A%2F%2Ffoobar.com%2F') end end context 'with a handle' do it 'returns the URL with the specified handle as a param' do url = helper.tweet_url(via: 'foobar') expect(url).to eq('https://twitter.com/intent/tweet?via=foobar') end end end end
unindented/unindented-rails
spec/lib/nokogiri_processor_spec.rb
<filename>spec/lib/nokogiri_processor_spec.rb describe NokogiriProcessor do let(:html) do <<-eos <h1>Foo</h1> eos end context 'with a CSS selector' do subject do NokogiriProcessor.new(css: 'h1') do |nodes| nodes.wrap '<div class="header"></div>' end end describe '#process' do it 'executes the specified block on matching nodes' do body = Capybara.string(subject.process(html)) expect(body).to have_xpath('//div[@class="header"]/h1') end end end context 'with a XPath selector' do subject do NokogiriProcessor.new(xpath: './/h1') do |nodes| nodes.wrap '<div class="header"></div>' end end describe '#process' do it 'executes the specified block on matching nodes' do body = Capybara.string(subject.process(html)) expect(body).to have_xpath('//div[@class="header"]/h1') end end end end
unindented/unindented-rails
lib/tasks/cucumber.rake
<gh_stars>0 unless ARGV.any? {|a| a =~ /^gems/} vendored_cucumber_bin = Dir["#{Rails.root}/vendor/{gems,plugins}/cucumber*/bin/cucumber"].first $LOAD_PATH.unshift(File.dirname(vendored_cucumber_bin) + '/../lib') unless vendored_cucumber_bin.nil? begin require 'cucumber/rake/task' namespace :cucumber do Cucumber::Rake::Task.new(:ok, 'Run features that should pass') do |t| t.binary = vendored_cucumber_bin t.fork = true t.profile = 'default' end Cucumber::Rake::Task.new(:wip, 'Run features that are being worked on') do |t| t.binary = vendored_cucumber_bin t.fork = true t.profile = 'wip' end Cucumber::Rake::Task.new(:rerun, 'Record failing features and run only them if any exist') do |t| t.binary = vendored_cucumber_bin t.fork = true t.profile = 'rerun' end desc 'Run all features' task :all => [:ok, :wip] task :statsetup do require 'rails/code_statistics' ::STATS_DIRECTORIES << %w(Cucumber\ features features) if File.exist?('features') ::CodeStatistics::TEST_TYPES << "Cucumber features" if File.exist?('features') end end desc 'Alias for cucumber:ok' task :cucumber => 'cucumber:ok' task :stats => 'cucumber:statsetup' task :default => :cucumber rescue LoadError desc 'Cucumber not installed' task :cucumber do abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin.' end end end
unindented/unindented-rails
app/decorators/model_decorator.rb
class ModelDecorator < Draper::Decorator include Draper::LazyHelpers end
unindented/unindented-rails
spec/models/content_spec.rb
describe Content do describe '#valid?' do it 'fails with no title' do expect(FactoryGirl.build(:content, title: nil)).to have(1).error_on(:title) end it 'fails with no body' do expect(FactoryGirl.build(:content, body: nil)).to have(1).error_on(:body) end it 'fails with no path' do expect(FactoryGirl.build(:content, path: nil)).to have(1).error_on(:path) end it 'fails with no locator' do expect(FactoryGirl.build(:content, locator: nil)).to have(1).error_on(:locator) end it 'fails with no category' do expect(FactoryGirl.build(:content, category: nil)).to have(1).error_on(:category) end end describe '#body_html' do it 'gets generated before save' do content = FactoryGirl.create(:content, body: "*Foo bar*") expect(content.body_html).to include("<p><em>Foo bar</em></p>") end end describe '#previous' do context 'when there is no previous content' do it 'returns nil' do content1 = FactoryGirl.create(:content, category: :foobar, date: 3.day.ago) content2 = FactoryGirl.create(:content, category: :foobar, date: 2.days.ago) content3 = FactoryGirl.create(:content, category: :foobar, date: 1.days.ago) content4 = FactoryGirl.create(:content, category: :bazqux, date: 4.day.ago) expect(content1.previous).to be_nil end end context 'when there is previous content' do it 'returns the previous content' do content1 = FactoryGirl.create(:content, category: :foobar, date: 3.day.ago) content2 = FactoryGirl.create(:content, category: :foobar, date: 2.days.ago) content3 = FactoryGirl.create(:content, category: :foobar, date: 1.days.ago) content4 = FactoryGirl.create(:content, category: :bazqux, date: 3.day.ago) expect(content2.previous).to eq(content1) end end end describe '#next' do context 'when there is no next content' do it 'returns nil' do content1 = FactoryGirl.create(:content, category: :foobar, date: 3.day.ago) content2 = FactoryGirl.create(:content, category: :foobar, date: 2.days.ago) content3 = FactoryGirl.create(:content, category: :foobar, date: 1.days.ago) content4 = FactoryGirl.create(:content, category: :bazqux, date: 0.days.ago) expect(content3.next).to be_nil end end context 'when there is next content' do it 'returns the next content' do content1 = FactoryGirl.create(:content, category: :foobar, date: 3.day.ago) content2 = FactoryGirl.create(:content, category: :foobar, date: 2.days.ago) content3 = FactoryGirl.create(:content, category: :foobar, date: 1.days.ago) content4 = FactoryGirl.create(:content, category: :bazqux, date: 1.days.ago) expect(content2.next).to eq(content3) end end end describe '#to_param' do it 'returns the locator' do content = FactoryGirl.build(:content, locator: 'foo/bar') expect(content.to_param).to eq('foo/bar') end end end
unindented/unindented-rails
app/helpers/url_helper.rb
<reponame>unindented/unindented-rails module UrlHelper def absolute_url(path, opts = {}) url_with_params("#{host_text}#{path}", opts) end def current_url(opts = {}) url_with_params("#{host_text}#{request.original_fullpath}", opts) end def email_url(email = email_text, opts = {}) url_with_params("mailto:#{email}", opts) end def github_url(handle = github_text, opts = {}) url_with_params("https://github.com/#{handle}", opts) end def twitter_url(handle = twitter_text, opts = {}) url_with_params("https://twitter.com/#{handle}", opts) end def tweet_url(opts = {}) url_with_params("https://twitter.com/intent/tweet", opts) end private def url_with_params(url, opts = {}) "#{url}#{opts.present? ? "?#{opts.to_query}" : ''}" end end
unindented/unindented-rails
spec/routing/experiments_routing_spec.rb
describe ExperimentsController do describe 'routing' do it 'routes `/experiments` to #show' do expect(get '/experiments/').to route_to('experiments#show') end it 'routes `/experiments/2013` to #show' do expect(get '/experiments/2013/').to route_to( 'experiments#show', year: '2013') end it 'routes `/experiments/2013/02` to #show' do expect(get '/experiments/2013/02/').to route_to( 'experiments#show', year: '2013', month: '02') end it 'routes `/experiments/2013/02/01` to #show' do expect(get '/experiments/2013/02/01/').to route_to( 'experiments#show', year: '2013', month: '02', day: '01') end end describe 'named routes' do it 'routes `experiments_path` to #show' do expect(get experiments_path).to route_to('experiments#show') end it 'routes `/experiments/2013` to #show' do expect(get archive_experiments_path(year: '2013')).to route_to( 'experiments#show', year: '2013') end it 'routes `/experiments/2013/02` to #show' do expect(get archive_experiments_path(year: '2013', month: '02')).to route_to( 'experiments#show', year: '2013', month: '02') end it 'routes `/experiments/2013/02/01` to #show' do expect(get archive_experiments_path(year: '2013', month: '02', day: '01')).to route_to( 'experiments#show', year: '2013', month: '02', day: '01') end end end
unindented/unindented-rails
app/helpers/twitter_helper.rb
module TwitterHelper def twitter_card_meta_tag(name, value, options = {}) tag(:meta, { name: "twitter:#{name}", content: value }.merge!(options.symbolize_keys)) end end
unindented/unindented-rails
lib/body_processor.rb
<filename>lib/body_processor.rb require 'kramdown_processor' require 'nokogiri_processor' require 'pygments_processor' class BodyProcessor def initialize(opts = {}) @kramdown = KramdownProcessor.new(opts[:kramdown]) @nokogiri = NokogiriProcessor.new(opts[:nokogiri]) do |nodes| nodes.wrap '<div class="overflow"></div>' end @pygments = PygmentsProcessor.new(opts[:pygments]) end def process(body, opts = {}) body = @kramdown.process(body) body = @nokogiri.process(body) body = @pygments.process(body) end end
unindented/unindented-rails
spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test' require 'simplecov' require 'spec_helper' require File.expand_path('../../config/environment', __FILE__) require 'rspec/rails' require 'capybara/rails' require 'capybara/rspec' Capybara.javascript_driver = :poltergeist Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.use_transactional_fixtures = false config.infer_base_class_for_anonymous_controllers = false config.infer_spec_type_from_file_location! end
unindented/unindented-rails
lib/body_summarizer.rb
<reponame>unindented/unindented-rails require 'nokogiri' class BodySummarizer DEFAULT_OPTS = { xpath: './/p', range: 0...2 } def initialize(opts = {}) @opts = DEFAULT_OPTS.merge(opts) end def summarize_text(html) summarize(html).map(&:text).join(' ') end def summarize_html(html) summarize(html).map(&:to_html).join(' ') end private def summarize(html) doc = ::Nokogiri::HTML::DocumentFragment.parse(html) nodes = [] nodes.push(*(doc.css(@opts[:css]))) unless @opts[:css].nil? nodes.push(*(doc.xpath(@opts[:xpath]))) unless @opts[:xpath].nil? nodes.slice(@opts[:range]) end end
unindented/unindented-rails
app/decorators/tag_decorator.rb
class TagDecorator < ModelDecorator delegate_all def route tag_path(self) end def parent_route tags_path end end
unindented/unindented-rails
config/initializers/settings.rb
config = RecursiveOpenStruct.new(YAML.load_file(Rails.root.join('config', 'settings.yml'))) SETTINGS = config.send(Rails.env)
unindented/unindented-rails
spec/models/content_extendable_spec.rb
describe Content do describe '#extensions_list' do let(:extensions) do extensions = [] extensions << FactoryGirl.build(:extension, name: 'Foo') extensions << FactoryGirl.build(:extension, name: 'Bar') end it 'returns an empty array when there are no extensions' do content = FactoryGirl.build(:content) expect(content.extensions_list).to be_empty end it 'returns an array with the extension names' do content = FactoryGirl.build(:content) content.extensions << extensions expect(content.extensions_list).to include('Foo', 'Bar') end end describe '#extensions_list=' do let(:extensions) do extensions = [] extensions << FactoryGirl.build(:extension, name: 'Foo') extensions << FactoryGirl.build(:extension, name: 'Bar') end it 'clears all previous extensions' do content = FactoryGirl.build(:content) content.extensions << extensions content.extensions_list = [] expect(content.extensions_list).to be_empty end it 'assigns the specified extensions' do content = FactoryGirl.build(:content) content.extensions << extensions content.extensions_list = ['Foo', 'Baz'] expect(content.extensions_list).to include('Foo', 'Baz') expect(content.extensions_list).to_not include('Bar') end end end
unindented/unindented-rails
spec/helpers/meta_helper_spec.rb
<reponame>unindented/unindented-rails describe MetaHelper do describe '#humans_link_tag' do it 'returns a link to a `humans.txt` file' do link = Capybara.string(helper.humans_link_tag('/humans.txt')) expect(link).to have_xpath("//link[@rel='help']", visible: false) expect(link).to have_xpath("//link[@href='/humans.txt']", visible: false) end end describe '#icon_link_tag' do it 'returns a link to a favicon' do link = Capybara.string(helper.icon_link_tag(:png, '/favicon.png', sizes: '32x32')) expect(link).to have_xpath("//link[@rel='icon']", visible: false) expect(link).to have_xpath("//link[@type='image/png']", visible: false) expect(link).to have_xpath("//link[@href='/favicon.png']", visible: false) expect(link).to have_xpath("//link[@sizes='32x32']", visible: false) end end describe '#apple_icon_link_tag' do it 'returns a link to an Apple touch icon' do link = Capybara.string(helper.apple_icon_link_tag(:png, '/favicon.png', sizes: '32x32')) expect(link).to have_xpath("//link[@rel='apple-touch-icon-precomposed']", visible: false) expect(link).to have_xpath("//link[@type='image/png']", visible: false) expect(link).to have_xpath("//link[@href='/favicon.png']", visible: false) expect(link).to have_xpath("//link[@sizes='32x32']", visible: false) end end describe '#navigation_link_tag' do it 'returns a navigation link' do link = Capybara.string(helper.navigation_link_tag(:up, '/foobar/')) expect(link).to have_xpath("//link[@rel='up']", visible: false) expect(link).to have_xpath("//link[@href='/foobar/']", visible: false) end end describe '#feed_link_tag' do it 'returns a feed link' do link = Capybara.string(helper.feed_link_tag(:atom)) expect(link).to have_xpath("//link[@rel='alternate']", visible: false) expect(link).to have_xpath("//link[@type='application/atom+xml']", visible: false) expect(link).to have_xpath("//link[@href='/feed.atom']", visible: false) end end end
unindented/unindented-rails
app/helpers/open_graph_helper.rb
<filename>app/helpers/open_graph_helper.rb module OpenGraphHelper def open_graph_meta_tag(name, value, options = {}) tag(:meta, { property: "og:#{name}", content: value }.merge!(options.symbolize_keys)) end end
unindented/unindented-rails
spec/decorators/tag_decorator_spec.rb
<gh_stars>0 describe TagDecorator do describe '#route' do it 'returns the route for the tag' do tag = FactoryGirl.create(:tag).decorate expect(tag.route).to eq(helpers.tag_path(tag.locator)) end end describe '#parent_route' do it 'returns the parent route for the tag' do tag = FactoryGirl.create(:tag).decorate expect(tag.parent_route).to eq(helpers.tags_path) end end end
unindented/unindented-rails
features/support/matchers/have_before.rb
<reponame>unindented/unindented-rails RSpec::Matchers.define(:have_before) do |earlier_content, later_content| match do |page| page.body.index(earlier_content) < page.body.index(later_content) end end
unindented/unindented-rails
app/helpers/script_helper.rb
<reponame>unindented/unindented-rails<gh_stars>0 module ScriptHelper def webfonts_script_tag config = content_tag(:script) do %Q{ var WebFontConfig = #{webfonts_config}; }.html_safe end library = javascript_include_tag(webfonts_url, async: true) (config + library).html_safe end def mathjax_script_tag config = content_tag(:script, type: 'text/x-mathjax-config') do %Q{ MathJax.Hub.Config(#{mathjax_config}); }.html_safe end library = javascript_include_tag(mathjax_url, async: true) (config + library).html_safe end def fixurl_script_tag config = content_tag(:script) do %Q{ var GOOG_FIXURL_LANG = (navigator.language || '').slice(0, 2); var GOOG_FIXURL_SITE = location.host; }.html_safe end library = javascript_include_tag(fixurl_url) (config + library).html_safe end def tagman_noscript_tag content_tag(:noscript) do content_tag(:iframe, { src: tagman_url_nojs(tagman_id), height: 0, width: 0, style: 'display: none; visibility: hidden;' }) {} end end def tagman_script_tag config = content_tag(:script) do %Q{ var dataLayer = [{ 'gtm.start': new Date().getTime(), event: 'gtm.js' }]; }.html_safe end library = javascript_include_tag(tagman_url_js(tagman_id), async: true) (config + library).html_safe end private def webfonts_config webfonts_config_process(SETTINGS.webfonts.config_as_a_hash).to_json end def webfonts_config_process(config) config.reduce({}) do |memo, (k, v)| memo[k] = if k == 'families' v.map { |family, styles| "#{family}:#{styles.join(',')}" } else webfonts_config_process(v) end memo end end def webfonts_url SETTINGS.webfonts.url end def mathjax_config mathjax_config_process(SETTINGS.mathjax.config_as_a_hash).to_json end def mathjax_config_process(config) config.deep_transform_keys { |k| k.camelize(:lower) } end def mathjax_url SETTINGS.mathjax.url end def fixurl_url SETTINGS.fixurl.url end def tagman_url_nojs(id) "#{SETTINGS.tagman.url_nojs}?id=#{id}" end def tagman_url_js(id) "#{SETTINGS.tagman.url_js}?id=#{id}" end def tagman_id SETTINGS.tagman.id end end
unindented/unindented-rails
app/models/content.rb
<reponame>unindented/unindented-rails class Content < ActiveRecord::Base include Taggable include Extendable include Processable include Summarizable paginates_per 6 default_scope -> { published.order(date: :desc, title: :asc) } scope :prioritized, -> { reorder(featured: :desc, date: :desc, title: :asc) } scope :published, -> { where(published: true) } scope :featured, -> { where(featured: true) } scope :categorized, ->(category) { where(category: category) } scope :between, ->(range) { range.present? ? where(date: range) : all } validates :title, :body, :path, :locator, :category, presence: true before_save :update_body, :update_abstract def previous # Only works because content is loaded into the database in the expected order. self.class .categorized(category) .where('id < :id', id: id) .reorder('id DESC') .first end def next # Only works because content is loaded into the database in the expected order. self.class .categorized(category) .where('id > :id', id: id) .reorder('id ASC') .first end def to_param self.locator end private def update_body self.body_html = process(self.body) end def update_abstract self.abstract = summarize_text(self.body_html) self.abstract_html = summarize_html(self.body_html) end end
unindented/unindented-rails
spec/controllers/errors_controller_spec.rb
<reponame>unindented/unindented-rails describe ErrorsController do describe 'GET show' do context 'with a 404 error' do it 'has a 200 status code' do get :show, error: '404' expect(response.status).to eq(200) end end context 'with a 500 error' do it 'has a 200 status code' do get :show, error: '500' expect(response.status).to eq(200) end end end end
unindented/unindented-rails
app/controllers/home_controller.rb
<gh_stars>0 class HomeController < ApplicationController respond_to :html def show @about = Content .find_by!(locator: 'about') .decorate @contents = Content .categorized([:articles, :experiments]) .prioritized .limit(6) .decorate respond_with @contents, layout: 'home' end end
unindented/unindented-rails
spec/lib/body_summarizer_spec.rb
describe BodySummarizer do let(:html) do <<-eos <h1>Foo</h1> <p>Bar</p> <p>Baz</p> <p>Qux</p> eos end context 'without options' do subject do BodySummarizer.new end describe '#summarize_text' do it 'extracts the text from the first two paragraphs' do abstract = subject.summarize_text(html) expect(abstract).to eq('Bar Baz') end end describe '#summarize_html' do it 'extracts the HTML from the first two paragraphs' do abstract = Capybara.string(subject.summarize_html(html)) expect(abstract).to have_xpath('//p', count: 2) expect(abstract.text).to eq('Bar Baz') end end end context 'with a CSS selector and a range' do subject do BodySummarizer.new(css: 'p', range: 1...2) end describe '#summarize_text' do it 'extracts the text from the specified paragraph' do abstract = subject.summarize_text(html) expect(abstract).to eq('Baz') end end describe '#summarize_html' do it 'extracts the HTML from the specified paragraph' do abstract = Capybara.string(subject.summarize_html(html)) expect(abstract).to have_xpath('//p', count: 1) expect(abstract.text).to eq('Baz') end end end context 'with a XPath selector and a range' do subject do BodySummarizer.new(css: 'p', range: 1...2) end describe '#summarize_text' do it 'extracts the text from the specified paragraph' do abstract = subject.summarize_text(html) expect(abstract).to eq('Baz') end end describe '#summarize_html' do it 'extracts the HTML from the specified paragraph' do abstract = Capybara.string(subject.summarize_text(html)) expect(abstract).to have_xpath('//p', count: 1) expect(abstract.text).to eq('Baz') end end end end
unindented/unindented-rails
spec/models/tag_spec.rb
describe Tag do describe '.counts' do it 'returns the content count for each tag' do tags = FactoryGirl.create_list(:tag, 2) contents = FactoryGirl.create_list(:content, 2) contents.first.tags << [tags.first] contents.last.tags << [tags.first, tags.last] counts = Tag.counts.reorder('id') expect(counts.first.count).to eq(2) expect(counts.last.count).to eq(1) end end describe '#valid?' do it 'fails with no name' do expect(FactoryGirl.build(:tag, name: nil)).to have(1).error_on(:name) end it 'fails with duplicate name' do tag = FactoryGirl.create(:tag) expect(FactoryGirl.build(:tag, name: tag.name)).to have(1).error_on(:name) end end describe '#locator' do it 'gets generated based on the name' do tag = FactoryGirl.create(:tag, name: 'FooBar') expect(tag.locator).to eq('foobar') end end describe '#to_param' do it 'returns the locator' do tag = FactoryGirl.create(:tag, name: 'FooBar') expect(tag.to_param).to eq('foobar') end end end
unindented/unindented-rails
spec/helpers/microsoft_helper_spec.rb
describe MicrosoftHelper do describe '#msft_app_name_meta_tag' do it 'returns a Microsoft App meta tag with the application name' do meta = Capybara.string(helper.msft_app_name_meta_tag('FooBar')) expect(meta).to have_xpath("//meta[@name='application-name']", visible: false) expect(meta).to have_xpath("//meta[@content='FooBar']", visible: false) end end describe '#msft_app_config_meta_tag' do it 'returns a Microsoft App meta tag with the configuration file' do meta = Capybara.string(helper.msft_app_config_meta_tag('/browserconfig.xml')) expect(meta).to have_xpath("//meta[@name='msapplication-config']", visible: false) expect(meta).to have_xpath("//meta[@content='/browserconfig.xml']", visible: false) end end end
unindented/unindented-rails
app/decorators/collection_decorator.rb
class CollectionDecorator < Draper::CollectionDecorator include Draper::LazyHelpers end
unindented/unindented-rails
db/migrate/20131201000005_create_content_extensions.rb
<reponame>unindented/unindented-rails class CreateContentExtensions < ActiveRecord::Migration def change create_table :content_extensions do |t| t.belongs_to :content, null: false, index: true t.belongs_to :extension, null: false, index: true end end end
unindented/unindented-rails
app/helpers/microsoft_helper.rb
<reponame>unindented/unindented-rails module MicrosoftHelper def msft_app_name_meta_tag(name, options = {}) tag(:meta, { name: 'application-name', content: name }.merge!(options.symbolize_keys)) end def msft_app_config_meta_tag(path, options = {}) tag(:meta, { name: 'msapplication-config', content: path }.merge!(options.symbolize_keys)) end end
unindented/unindented-rails
spec/helpers/link_helper_spec.rb
<gh_stars>0 describe LinkHelper do describe '#email_link' do before { allow(SETTINGS).to receive(:email) { '<EMAIL>' } } context 'without text' do it 'returns a link with the configured email address' do link = Capybara.string(helper.email_link) expect(link).to have_xpath("//a[@href='mailto:<EMAIL>']") expect(link).to have_text('<EMAIL>') end end context 'with text' do it 'returns a link with the specified text' do link = Capybara.string(helper.email_link('Foo Bar')) expect(link).to have_xpath("//a[@href='mailto:<EMAIL>']") expect(link).to have_text('Foo Bar') end end context 'with a subject' do it 'returns a link with the specified subject as a param' do link = Capybara.string(helper.email_link('Foo Bar', subject: 'Baz')) expect(link).to have_xpath("//a[@href='mailto:<EMAIL>?subject=Baz']") expect(link).to have_text('Foo Bar') end end end describe '#github_link' do before { allow(SETTINGS).to receive(:github) { 'foobar' } } context 'without text' do it 'returns a link to the configured GitHub account' do link = Capybara.string(helper.github_link) expect(link).to have_xpath("//a[@href='https://github.com/foobar']") expect(link).to have_text('@foobar') end end context 'with text' do it 'returns a link with the specified text' do link = Capybara.string(helper.github_link('Foo Bar')) expect(link).to have_xpath("//a[@href='https://github.com/foobar']") expect(link).to have_text('Foo Bar') end end end describe '#twitter_link' do before { allow(SETTINGS).to receive(:twitter) { 'foobar' } } context 'without text' do it 'returns a link to the configured Twitter account' do link = Capybara.string(helper.twitter_link) expect(link).to have_xpath("//a[@href='https://twitter.com/foobar']") expect(link).to have_text('@foobar') end end context 'with text' do it 'returns a link with the specified text' do link = Capybara.string(helper.twitter_link('Foo Bar')) expect(link).to have_xpath("//a[@href='https://twitter.com/foobar']") expect(link).to have_text('Foo Bar') end end end describe '#tweet_link' do before { allow(SETTINGS).to receive(:twitter) { 'foobar' } } context 'without text' do it 'returns a link to the `tweet` intent' do link = Capybara.string(helper.tweet_link) expect(link).to have_xpath("//a[@href='https://twitter.com/intent/tweet']") expect(link).to have_text('@foobar') end end context 'with text' do it 'returns a link with the specified text' do link = Capybara.string(helper.tweet_link('Foo Bar')) expect(link).to have_xpath("//a[@href='https://twitter.com/intent/tweet']") expect(link).to have_text('Foo Bar') end end context 'with a URL' do it 'returns a link with the specified URL as a param' do link = Capybara.string(helper.tweet_link('Foo Bar', url: 'http://foobar.com/')) expect(link).to have_xpath("//a[@href='https://twitter.com/intent/tweet?url=http%3A%2F%2Ffoobar.com%2F']") expect(link).to have_text('Foo Bar') end end context 'with a handle' do it 'returns a link with the specified handle as a param' do link = Capybara.string(helper.tweet_link('Foo Bar', via: 'foobar')) expect(link).to have_xpath("//a[@href='https://twitter.com/intent/tweet?via=foobar']") expect(link).to have_text('Foo Bar') end end end end
unindented/unindented-rails
app/helpers/meta_helper.rb
module MetaHelper def humans_link_tag(source, options = {}) tag(:link, { rel: 'help', type: 'text/plain', href: source }.merge!(options.symbolize_keys)) end def icon_link_tag(format, url_options = {}, tag_options = {}) tag(:link, { rel: 'icon', type: Mime::Type.lookup_by_extension(format.to_s).to_s, href: url_options.is_a?(Hash) ? url_for(url_options.merge(only_path: false)) : url_options }.merge!(tag_options.symbolize_keys)) end def apple_icon_link_tag(format, url_options = {}, tag_options = {}) icon_link_tag(format, url_options, tag_options.merge(rel: 'apple-touch-icon-precomposed')) end def navigation_link_tag(rel, url_options = {}, tag_options = {}) tag(:link, { rel: rel, href: url_options.is_a?(Hash) ? url_for(url_options.merge(only_path: false)) : url_options }.merge!(tag_options.symbolize_keys)) end def feed_link_tag(type) auto_discovery_link_tag(type, feed_path(format: type, trailing_slash: false), type: Mime::Type.lookup_by_extension(type.to_s).to_s, title: t("shared.misc.#{type}")) end end
unindented/unindented-rails
spec/controllers/tags_controller_spec.rb
describe TagsController do describe 'GET index' do let!(:tags) { FactoryGirl.create_list(:tag, 2) } it 'has a 200 status code' do get :index expect(response.status).to eq(200) end end describe 'GET show' do let!(:tag) { FactoryGirl.create(:tag, name: 'FooBar') } context 'with incorrect locator' do it 'has a 404 status code' do get :show, locator: 'bazqux' expect(response.status).to eq(404) end end context 'with correct locator' do it 'has a 200 status code' do get :show, locator: 'foobar' expect(response.status).to eq(200) end end end end
unindented/unindented-rails
app/models/concerns/extendable.rb
<gh_stars>0 module Extendable extend ActiveSupport::Concern included do has_many :content_extensions has_many :extensions, through: :content_extensions end def extensions_list self.extensions.map(&:name) end def extensions_list=(names) self.extensions = (names || []).map { |name| Extension.find_or_create_by!(name: name) } end end
unindented/unindented-rails
lib/nokogiri_processor.rb
require 'nokogiri' class NokogiriProcessor DEFAULT_OPTS = { } def initialize(opts = {}, &block) @opts = DEFAULT_OPTS.merge(opts).select { |key, value| [:css, :xpath].include?(key) } @block = block end def process(str) doc = ::Nokogiri::HTML::DocumentFragment.parse(str) @block.call(doc.css(@opts[:css])) unless @opts[:css].nil? @block.call(doc.xpath(@opts[:xpath])) unless @opts[:xpath].nil? doc.to_html end end