repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
Rainiugnas/password_manager
lib/password_manager/version.rb
<gh_stars>0 # frozen_string_literal: true module PasswordManager # Gem version number VERSION = '1.2.0' end
Rainiugnas/password_manager
lib/cli/input/stop.rb
# frozen_string_literal: true module Cli module Input # Model to stop the program execution and wait for input # @attr_reader [String] value Data from input, alway nil # @attr_reader [String] error Alway nil # @attr_reader [Boolean] success Alway true class Stop attr_reader :value, :error, :success # Stop the execution with the given message and wait for input # @param [String] message Message displayed to ask input def initialize message press_to_continue! message @success = true end private # Stop the execution with the given message and wait for input # @param [String] message def press_to_continue! message print message STDIN.gets end end end end
Rainiugnas/password_manager
spec/matcher/be_crypter.rb
# frozen_string_literal: true # Success if all the site in the expected array have # the same attribute than the site in the actual array RSpec::Matchers.define :be_crypter do match do |actual| actual.respond_to?(:encrypt) && actual.respond_to?(:decrypt) end end
Rainiugnas/password_manager
spec/spec_helper.rb
# frozen_string_literal: true # rubocop:disable Style/MixinUsage # Launch test coverage require 'simplecov' SimpleCov.start require 'bundler/setup' # Lib require 'password_manager' require 'cli' require 'cli_file_crypter' require 'byebug' # Spec tools require 'dummies/dummy_crypter' require 'matcher/match_site_array' require 'matcher/be_crypter' # Use the lib element without namespace include PasswordManager include PasswordManager::Crypter include Cli include Cli::Input RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.rspec_status' # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
Rainiugnas/password_manager
spec/lib/password_manager/converter_spec.rb
<gh_stars>0 # frozen_string_literal: true # rubocop:disable Metrics/BlockLength require 'json' RSpec.describe Converter do let(:crypter1) { DummyCrypter.new 'c1' } let(:crypter2) { DummyCrypter.new 'c1v2' } let(:crypters) { [crypter1, crypter2] } let(:site) { PasswordManager::Site.new 'name', 'user', 'password', 'email' => 'user_email' } let(:array) { [site] } let(:json) do JSON.generate 'name' => { 'email': 'user_email', 'username' => 'user', 'password' => 'password' } end let(:encrypted_data) { "c1v2:c1:#{json}" } let(:converter) { Converter.from_array array, crypters } describe '.from_crypt' do it 'should set the converter array from the given encrypted data and crypters' do expect(Converter.from_crypt(encrypted_data, crypters).to_array).to match_site_array array end end describe '.from_json' do it 'should set the converter array from the given json' do expect(Converter.from_json(json, crypters).to_array).to match_site_array array end context 'when the given json is invalid' do it 'should raise an exception' do expect { Converter.from_json 'invalid', crypters }.to raise_exception ConverterError end end end describe '.from_array' do it 'should set the converter array with the given array' do expect(Converter.from_array(array, crypters).to_array).to eq array end end describe '#to_array' do it 'should return the given array' do expect(converter.to_array).to eq array end end describe '#to_json' do it 'should convert the array in json' do expect(converter.to_json).to eq json end end describe '#to_crypt' do it 'should encryt the array with the given encrypters' do expect(converter.to_crypt).to eq encrypted_data end end end
Rainiugnas/password_manager
lib/password_manager/site.rb
# frozen_string_literal: true module PasswordManager # Model for site data. # @attr_reader [String] name The site name, also the key use to store the site (required) # @attr_reader [String] user The username associated to the site (required) # @attr_reader [String] password The password associated to the site # @attr_reader [Hash(String)] extra Any other data related to the site as email or note # @attr_reader [String] error Hold the validation error message (nil if no error) # @attr_reader [Boolean] success True if the validation success else false class Site attr_reader :name, :user, :password, :extra attr_reader :success, :error # Initialize the attributes and check their validity # @param [String] name # @param [String] user # @param [String] password # @param [Hash(String)] extra def initialize name, user, password, extra = {} @name = name @user = user @password = password @extra = extra @success = true valid_name! valid_user_or_email! end private # Check if the name is present # @return [Boolean] True if the site name is present else false def valid_name! return unless @name.blank? @success = false @error = 'Error: site name must be present' end # Check if the user is present # @return [Boolean] True if the user is present else false def valid_user_or_email! return unless @user.blank? && @extra['email'].blank? @success = false @error = 'Error: user name or extra email must be present' end end end
Rainiugnas/password_manager
spec/lib/cli/input/site_spec.rb
# frozen_string_literal: true RSpec.describe Cli::Input::Site do let(:message) { "sitename: \nusername: \npassword: \n" } let(:input1) { "site name\n" } let(:input2) { "user name\n" } let(:input3) { "<PASSWORD>" } let(:site) { described_class.new } before(:each) do expect($stdin).to receive(:gets).and_return input1 expect($stdin).to receive(:gets).and_return input2 expect($stdin).to receive(:noecho).and_return input3 expect { site }.to output(message).to_stdout end describe 'constructor' do it 'should set the value from the input and remove the \n' do expect(site.name).to eq 'site name' expect(site.user).to eq 'user name' expect(site.password).to eq 'password' end end end
Rainiugnas/password_manager
spec/lib/cli_file_crypter_spec.rb
<filename>spec/lib/cli_file_crypter_spec.rb # frozen_string_literal: true # rubocop:disable Metrics/BlockLength RSpec.describe CliFileCrypter do describe '.interupt!' do it 'should raise an password manager exception with the given message' do expect { described_class.interupt! 'message' }.to raise_exception 'message' end end describe '.run' do let(:crypter1) { Aes.new password } let(:crypter2) { PasswordManager::Crypter::Base64.new } let(:crypters) { [crypter1, crypter2] } let(:converter) { Converter.from_array sites, crypters } let(:raw_file) { 'file data' } let(:crypt_file) { 'base64:aes:file data' } let(:readable?) { true } let(:path) { 'file/path' } let(:file) { crypt_file } let(:password) { 'password' } let(:password_error) { '<PASSWORD>' } let(:password_success?) { true } before(:each) do allow(File).to receive(:read).with(path).and_return file allow(File).to receive(:readable?).and_return readable? allow(File).to receive(:writable?).and_return true allow(Aes).to receive(:new).with(password).and_return DummyCrypter.new 'aes' allow(PasswordManager::Crypter::Base64).to receive(:new).and_return DummyCrypter.new 'base64' dummy_password = double(value: password, success: password_success?, error: password_error) allow(PasswordConfirmation).to receive(:new).and_return dummy_password stub_const 'ARGV', %w(rspec).concat(argv) end describe 'storage error' do let(:readable?) { false } let(:argv) { %w(-e -f).push path } it 'should print the error' do message = 'Error: the given file have not read and write right' expect { described_class.run }.to output(message).to_stdout end end describe 'option error' do context 'with invalid action number' do let(:argv) { %w(-e -d -f).push path } it 'should print the error' do message = <<~MSG invalid option: you must set one (no more) of the following options: --encrypt, --decrypt, --show, --add, --tmp and --list MSG expect { described_class.run }.to output(message).to_stdout end end context 'with other action than encrypt or decrypt' do let(:argv) { %w(-l -f).push path } it 'should print the error' do msg = 'Option must be file and either encrypt or decrypt. Other option are not suported.' expect { described_class.run }.to output(msg).to_stdout end end end describe 'password error' do let(:argv) { %w(-e -f).push path } let(:password_success?) { false } it 'should print the error' do expect { described_class.run }.to output(password_error).to_stdout end end describe 'encrypt' do let(:argv) { %w(-e -f).push path } let(:file) { raw_file } it 'should encrypt the file' do expect(File).to receive(:write).with path, crypt_file described_class.run end end describe 'decrypt' do let(:argv) { %w(-d -f).push path } let(:file) { crypt_file } it 'should decrypt the file' do expect(File).to receive(:write).with path, raw_file described_class.run end end end end
Rainiugnas/password_manager
spec/dummies/dummy_crypter.rb
# frozen_string_literal: true # Fake crypter, add / remove the salt at the begin of the given data class DummyCrypter def initialize salt; @salt = "#{salt}:" end def encrypt data; "#{@salt}#{data}" end def decrypt data; data[@salt.size..-1] end end
Rainiugnas/password_manager
spec/lib/cli/input/password_spec.rb
# frozen_string_literal: true RSpec.describe Password do let(:message) { 'ask message' } let(:input) { "input\n" } let(:password) { Password.new message } before(:each) do allow($stdin).to receive(:noecho).and_return input expect { password }.to output(message).to_stdout end describe 'constructor' do it 'should alway success' do expect(password.success).to be_truthy expect(password.error).to be_nil end it 'should set the value from the input and remove the \n' do expect(password.value).to eq 'input' end end end
Rainiugnas/password_manager
lib/cli/option.rb
<filename>lib/cli/option.rb # frozen_string_literal: true require 'optparse' # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/BlockLength # rubocop:disable Metrics/AbcSize module Cli # Use to parse the ARGV argument. # The file must be set and one action (encrypt, decrypt, list, show, add, tmp) must be set. # @attr_reader [String] file The file path or nil if not set (required) # @attr_reader [Boolean] encrypt True or false if not set # @attr_reader [Boolean] decrypt True or false if not set # @attr_reader [String] show Site name to find show or nil if not set # @attr_reader [Boolean] add True or false if not set # @attr_reader [Boolean] tmp True or false if not set # # @attr_reader [String] error Hold the validation error message (nil if no error) # @attr_reader [Boolean] success True if the validation success else false class Option attr_reader :file, :encrypt, :decrypt, :show, :add, :list, :tmp attr_reader :success, :error # Parse the ARGV and check that the file and the action is set. # Set the success to false and error message if the validation fail. def initialize @encrypt = @decrypt = @add = @list = @tmp = false @success = true build_parser.parse! valid_options! rescue OptionParser::MissingArgument, OptionParser::InvalidOption => exception @error = exception.message @success = false end private # @return [OptionParser] Build, set up and return the ARGV parser def build_parser OptionParser.new do |parser| parser.banner = 'Usage: example.rb -f ./filepath [options]' parser.separator '' parser.on( '-f', '--file path', '[required] Path of the file to encrypt / decrypt' ) { |option| @file = option.freeze } parser.on( '-e', '--encrypt', 'Encrypt the file with the rsa key' ) { @encrypt = true } parser.on( '-d', '--decrypt', 'Decrypt the file with the rsa key' ) { @decrypt = true } parser.on( '-s', '--show sitename', 'Show the information associate to the given site name' ) { |option| @show = option.freeze } parser.on( '-a', '--add', 'Add a site name and associate username / password to it' ) { @add = true } parser.on( '-l', '--list', 'List all the site name' ) { @list = true } parser.on( '-t', '--tmp', 'Decrypt the file temporary and the re encrypt it.' ) { @tmp = true } parser.on( '--help', 'Show the command usage.' ) { raise OptionParser::InvalidOption, parser.help } parser.separator <<~MSG The options --encrypt, --decrypt, --show, --add, --tmp and --list must be associate with a specific --file. It's a json file, the key is the site name and each key have an username and a password field. MSG end end # @raise [OptionParser::InvalidOption] When the file is not set # @raise [OptionParser::InvalidOption] When 0 or more than 1 action is set def valid_options! unless [@encrypt, @decrypt, @show, @add, @list, @tmp].one? raise OptionParser::InvalidOption, <<~MSG you must set one (no more) of the following options: --encrypt, --decrypt, --show, --add, --tmp and --list MSG end message = 'file (option -f / --file) must be provided' raise OptionParser::InvalidOption, message if @file.nil? end end end
Rainiugnas/password_manager
lib/password_manager/crypter/aes.rb
# frozen_string_literal: true require 'openssl' require 'digest/sha2' module PasswordManager module Crypter # Handle AES format class Aes # Set the password to salt encrypt / decrypt # @param [String] password def initialize password @cipher = OpenSSL::Cipher.new 'AES-256-CBC' @password = password end # @param [String] data Data to encrypt # @return [String] the AES encrypted data def encrypt(data) use_cipher_to :encrypt, data end # @param [String] data AES data to decrypt # @return [String] Result of the decryption # @raise [DecryptError] When the password is invalid def decrypt(data) use_cipher_to :decrypt, data rescue OpenSSL::Cipher::CipherError raise DecryptError, 'Error: the password use to encrypt is not the same than the decrypt password' end private def iv() @iv ||= key[0..15] end def key @key ||= begin digest = Digest::SHA256.new digest.update @password digest.digest end end # Dry the cipher usage for both decrypt and encrypt def use_cipher_to action, data @cipher.reset @cipher.send action @cipher.key = key @cipher.iv = iv @cipher.update(data) + @cipher.final end end end end
Rainiugnas/password_manager
lib/cli/input/password_confirmation.rb
# frozen_string_literal: true module Cli module Input # Model to retrieve password with confirmation from the input # @private @attr [Password] value Hold the password value # @attr_reader [String] error Hold the validation error message (nil if no error) # @attr_reader [Boolean] success True if the validation success else false class PasswordConfirmation attr_reader :error, :success # Ask for the password and confirmation with the given message. # Success if the confirmation is the same than the password. # @param [String] message The message displayed to ask the password def initialize message @value = Password.new message confirm_value! end # @return [String] The password value def value() @value.value end private # Set success to true if password is the same than confirmation. # Else set success to false and add error message. def confirm_value! confirmation = Password.new "Please enter password confirmation: \n" if value == confirmation.value @success = true else @error = 'The password does not match the confirmation' @success = false end end end end end
Rainiugnas/password_manager
spec/lib/cli/input/password_confirmation_spec.rb
# frozen_string_literal: true # rubocop:disable Metrics/BlockLength RSpec.describe PasswordConfirmation do let(:message) { 'ask message' } let(:input1) { 'input' } let(:input2) { 'input' } let(:confirmation) { PasswordConfirmation.new message } before(:each) do expect(Password).to receive(:new).with(message).and_return double(value: input1) expect(Password).to( receive(:new).with("Please enter password confirmation: \n").and_return double(value: input2) ) end describe 'constructor' do context 'when the confirmation match' do it 'should have the value of the first input' do expect(confirmation.value).to eq input1 end it 'should success' do expect(confirmation.success).to be_truthy end end context 'when the confirmation does not match' do let(:input1) { 'input' } let(:input2) { 'different' } it 'should have the value of the first input' do expect(confirmation.value).to eq input1 end it 'should not success' do expect(confirmation.success).to be_falsy end it 'should have an error' do expect(confirmation.error).to eq 'The password does not match the confirmation' end end end end
Rainiugnas/password_manager
spec/lib/password_manager/site_spec.rb
<gh_stars>0 # frozen_string_literal: true # rubocop:disable Metrics/BlockLength RSpec.describe PasswordManager::Site do let(:name) { 'site name' } let(:user) { 'user name' } let(:password) { '<PASSWORD>' } let(:extra) { { 'extra1' => '1', 'extra2' => '2' } } let(:site) { described_class.new name, user, password, extra } describe 'constructor' do it 'should set the attributes with the given values' do expect(site.name).to eq name expect(site.user).to eq user expect(site.password).to eq password end it 'should set the extra attributes' do expect(site.extra['extra1']).to eq '1' expect(site.extra['extra2']).to eq '2' end end describe 'validation' do context 'when all value filled' do it 'should success' do expect(site.success).to be_truthy end end describe 'name validation' do context 'when name is not present' do it 'should fail' do ['', nil].each do |name| site = described_class.new name, user, password expect(site.success).to be_falsy expect(site.error).to eq 'Error: site name must be present' end end end end describe 'user and extra email validation' do context 'when extra email is present but not user' do let(:extra) { { 'email' => 'user_email' } } it 'should success' do expect(site.success).to be_truthy end end context 'when user or email is not present' do it 'should fail' do ['', nil].each do |user| site = described_class.new name, user, password expect(site.success).to be_falsy expect(site.error).to eq 'Error: user name or extra email must be present' end end end end end end
Rainiugnas/password_manager
lib/password_manager.rb
<reponame>Rainiugnas/password_manager<gh_stars>0 # frozen_string_literal: true require 'active_support' require 'active_support/core_ext/object' require 'password_manager/version' require 'password_manager/exceptions' require 'password_manager/crypter' require 'password_manager/site' require 'password_manager/converter' # Root namespace. module PasswordManager end
Rainiugnas/password_manager
lib/cli/storage.rb
<filename>lib/cli/storage.rb # frozen_string_literal: true require 'json' module Cli # Model to handle file data access. # @attr [data] data Data read from to file or to write into the file # @private @attr [data] path Store the path of the file # @attr_reader [String] error Hold the validation error message (nil if no error) # @attr_reader [Boolean] success True if the validation success else false class Storage attr_accessor :data attr_reader :error, :success # Read the value of the file associated to the given path. # Set success to false if the file is not writable and readable. # @param [String] path The path associated to the targeted file def initialize path @path = path.freeze if valid_file? @data = File.read @path @success = true else @error = 'Error: the given file have not read and write right' @success = false end end # Read the file and store the data in data attribute def reload; @data = File.read @path end # Write the data into the file def save!; File.write @path, @data end private # @return [Boolean] True if the file is writable and readable else false def valid_file?; File.writable?(@path) && File.readable?(@path) end end end
Rainiugnas/password_manager
spec/lib/cli/input/stop_spec.rb
<reponame>Rainiugnas/password_manager<filename>spec/lib/cli/input/stop_spec.rb<gh_stars>0 # frozen_string_literal: true RSpec.describe Stop do let(:message) { 'press to continue' } let(:input) { "input\n" } let(:stop) { Stop.new message } before(:each) do allow($stdin).to receive(:gets).and_return input expect { stop }.to output(message).to_stdout end describe 'constructor' do it 'should alway success' do expect(stop.success).to be_truthy expect(stop.error).to be_nil end it 'should set the value to nil' do expect(stop.value).to be_nil end end end
Rainiugnas/password_manager
spec/matcher/match_site_array.rb
# frozen_string_literal: true # Success if all the site in the expected array have # the same attribute than the site in the actual array RSpec::Matchers.define :match_site_array do |expected| match do |actual| return false if actual.size != expected.size expected.each_with_index.map do |site, index| site.name == actual[index].name && site.user == actual[index].user && site.password == actual[index].password && site.extra == actual[index].extra end.all? end end
AmatsuZero/homebrew-tap
fppcli.rb
class Fppcli < Formula desc "CLI for Face++" homepage "https://github.com/AmatsuZero/FaceppSwift/releases" url "https://github.com/AmatsuZero/FaceppSwift.git", :tag => "0.1.8", :revision => "58c2c8ba5a552bc2a10d7b59944dbf333ba59055" head "https://github.com/AmatsuZero/FaceppSwift.git" depends_on :xcode => ["11.3.1", :build] def install system "make", "install", "prefix=#{prefix}" end test do system "#{bin}/fppcli", "--version" end end
smcingvale/dotfiles
vim/install.rb
#!/usr/bin/env ruby require "fileutils" require "open-uri" require "yaml" # TODO: If .vimrc or a symlink (or other vim dotfiles) already exists, # prompt the user to over-write. Dir['*.symlink'].each do |file| vim_symlink = File.join("#{Dir.home}", ".#{file[0, file.index('.')]}") unless File.symlink?(vim_symlink) File.symlink(File.join("#{__dir__}", "#{file}"), vim_symlink) end end FileUtils::mkdir_p(File.join(Dir.home, ".vim", "bundle")) FileUtils::mkdir_p(File.join(Dir.home, ".vim", "autoload")) open(File.join(Dir.home, ".vim", "autoload", "pathogen.vim"), "wb") do |pathogen| pathogen << open("https://raw.github.com/tpope/vim-pathogen/master/autoload/pathogen.vim").read end vim_plugins = YAML.load_file("plugins.yaml") vim_plugins.each do |plugin, clone_url| `git clone git://#{clone_url} #{File.join(Dir.home, ".vim", "bundle", plugin)}` end
hassox/pancake
lib/pancake/mixins/response_helper.rb
module Pancake module Mixins module ResponseHelper def headers @headers ||= {} end def status @status ||= 200 end def status=(st) @status = st end def redirect(location, status = 302) r = Rack::Response.new r.redirect(location, status) r end end end end
hassox/pancake
spec/pancake/middlewares/static_spec.rb
require 'spec_helper' describe Pancake::Middlewares::Static do before do @app = lambda{|e| Rack::Response.new("OK").finish} class ::FooBar < Pancake::Stack; end FooBar.roots << File.join(File.expand_path(File.dirname(__FILE__)), "../fixtures/middlewares") FooBar.push_paths(:public, ["public", "other_public"]) end after do clear_constants :FooBar end it "should require a stack to be passed to initialize" do static = Pancake::Middlewares::Static.new(@app, FooBar) static.stack.should == FooBar end it "should raise an error if not initialized with an object that includes Pancake::Paths" do lambda do Pancake::Middlewares::Static.new(@app, Object) end.should raise_error end it "should return the file if one is found in the first root" do static = Pancake::Middlewares::Static.new(@app, FooBar) env = Rack::MockRequest.env_for("/one.html") result = static.call(env) result[0].should == 200 body = result[2].body.map{|e| e}.join body.should include("In One") end it "should return the file if one is found in any of the roots" do static = Pancake::Middlewares::Static.new(@app, FooBar) env = Rack::MockRequest.env_for("/two.html") result = static.call(env) result[0].should == 200 body = result[2].body.map{|e| e}.join body.should include("In Two") end it "should pass through to the application if there is no file found" do static = Pancake::Middlewares::Static.new(@app, FooBar) env = Rack::MockRequest.env_for("/not_here.html") result = static.call(env) result[0].should == 200 body = result[2].body.map{|e| e}.join body.should == "OK" end it "should return a 404 if the file requested is outside the root directory" do static = Pancake::Middlewares::Static.new(@app, FooBar) file = "/../../../middlewares/static_spec.rb" result = FooBar.dirs_for(:public).map do |r| File.exists?(File.join(r, file)) end result.should include(true) env = Rack::MockRequest.env_for(file) result = static.call(env) result[2].body.map{|e| e}.join.should_not == "OK" result[0].should == 404 end it "should chomp a trailing slash" do static = Pancake::Middlewares::Static.new(@app, FooBar) file = "/two.html/" env = Rack::MockRequest.env_for(file) result = static.call(env) result[0].should == 200 body = result[2].body.map{|e| e}.join body.should include("In Two") end it "should unescape the file name" do static = Pancake::Middlewares::Static.new(@app, FooBar) file = "/foo%23bar.html" env = Rack::MockRequest.env_for(file) result = static.call(env) result[0].should == 200 body = result[2].body.map{|e| e}.join body.should include("escaped text is #") end end
hassox/pancake
lib/pancake/stack/defaults/tasks/pancake.rake
namespace :pancake do desc "symlink all public files to the current public directory" task :symlink_to_public do puts "Symlinking files to public" THIS_STACK.stackup THIS_STACK.symlink_public_files! puts "Done" end end
hassox/pancake
spec/pancake/mixins/request_helper_spec.rb
<filename>spec/pancake/mixins/request_helper_spec.rb require 'spec_helper' describe Pancake::Mixins::RequestHelper do before do class ::FooBar include Pancake::Mixins::RequestHelper end end after do clear_constants :FooBar end describe "logger" do before do @logger = mock("logger") @app = FooBar.new @app.env = {Pancake::Constants::ENV_LOGGER_KEY => @logger} end it "should access the rack.logger variable when using" do @logger.should_receive(:foo) @app.logger.foo end end describe "v" do it "should store the data put into v into the env" do env = {} foo = FooBar.new foo.env = env foo.v[:data] = :some_data env[Pancake::Mixins::RequestHelper::VARS_KEY][:data].should == :some_data end it "should store v as a Hashie" do env = {} foo = FooBar.new foo.env = env foo.v.should be_a_kind_of(Hashie::Mash) foo.v.data = :some_data foo.v.data.should == :some_data end end describe "configuration" do it "should get the configuraiton from the env" do env = { Pancake::Router::CONFIGURATION_KEY => "konfig"} foo = FooBar.new foo.env = env foo.configuration.should == "konfig" end end end
hassox/pancake
lib/pancake/hooks/inheritable_inner_classes.rb
module Pancake module Hooks module InheritableInnerClasses def self.extended(base) base.class_eval do extlib_inheritable_reader :_inhertiable_inner_classes, :_before_inner_class_inheritance @_inhertiable_inner_classes = [] @_before_inner_class_inheritance = [] end end # extended # Declare inner classes to be inherited when the outer class in inherited # The best way to show this is by example: # # @example # class Foo # inheritable_inner_class :Bar # # class Bar # end # end # # class Baz < Foo # # When Foo is inherited, the following occurs # class Bar < Foo::Bar; end # end # # This provides a more organic inheritance where the child gets their own # version of the inner class which is actually inherited from the parents inner class. # The inheritance chain remains intact. # # @api public # @since 0.1.0 # @author <NAME> def inheritable_inner_classes(*classes) _inhertiable_inner_classes unless classes.empty? _inhertiable_inner_classes << classes _inhertiable_inner_classes.flatten! end _inhertiable_inner_classes end # Runs any hooks before the inheritance of any inner classes # # @api public # @since 0.3.0 # @author <NAME> def before_inner_class_inheritance(&blk) _before_inner_class_inheritance << blk if blk _before_inner_class_inheritance end # The inherited hook that sets up inherited inner classes. Remember if you overwrite this method, you should # call super! # # @api private # @since 0.1.0 # @author <NAME> def inherited(base) super class_defs = inheritable_inner_classes.map do |klass| _before_inner_class_inheritance.each{|blk| blk.call(base.superclass) } "class #{klass} < superclass::#{klass}; end\n" end base.class_eval(class_defs.join) end end # InheritableInnerClasses end # Hooks end # Pancake
hassox/pancake
lib/pancake/mixins/url.rb
module Pancake module Url module Generation def url(name, opts = {}) konfig = request.env[Pancake::Router::CONFIGURATION_KEY] konfig.router.generate(name, opts) end end # Generation end # Url end # Pancake
hassox/pancake
lib/pancake/stack/configuration.rb
<filename>lib/pancake/stack/configuration.rb<gh_stars>1-10 module Pancake class Stack inheritable_inner_classes :Configuration class Configuration < Pancake::Configuration::Base end # Provides access to the configuration block for the stack. # If a block is provided, it opens the specific configuration instances anonymous class # and allows you to edit it. # If no block is provided, it just returns the configuration object. # # :api: public def self.configuration(label = self, &block) config = Pancake.configuration.configs[label] ||= self::Configuration.new config.class.class_eval(&block) if block config end def configuration(label = self.class) yield self.class.configuration(label) if block_given? self.class.configuration(label) end end # Stack end # Pancake #################### # Setup the default configuration for each stack class Pancake::Stack::Configuration default :router, Proc.new{ _router }, "The router for this stack" def _router @_router ||= begin unless stack.nil? r = stack.router.clone r.stack = stack r.configuration = self r end end end end
hassox/pancake
spec/pancake/stack/stack_configuration_spec.rb
<gh_stars>1-10 require 'spec_helper' describe "pancake stack configuration" do before(:each) do Pancake.configuration.stacks.clear Pancake.configuration.configs.clear class ::FooStack < Pancake::Stack end FooStack.roots << Pancake.get_root(__FILE__) end after(:each) do clear_constants(:FooStack) end it "should provide access to the stack configuration" do FooStack.configuration.class.should inherit_from(Pancake::Configuration::Base) end it "should allow me to set defaults on a stack" do FooStack.configuration do default :foo, :bar default :bar, "Foo Bar Man" end FooStack.configuration.foo.should == :bar FooStack.configuration.bar.should == "Foo Bar Man" end it "should allow me to extend the configuration" do class Pancake::Stack::Configuration default :foo, :bar, "I am a foo default" default :bar do foobar end def foobar :foobar end end class FooBarStack < Pancake::Stack; end FooBarStack.configuration.foo.should == :bar FooBarStack.configuration.bar.should == :foobar end describe "configurations" do it "should provide a configuration object for the stack" do app = FooStack.stackup app.configuration.should be_an_instance_of(FooStack::Configuration) end it "should put a copy of the application at the stack identified by the class" do router = FooStack.stackup Pancake.configuration.stacks[FooStack].should be_an_instance_of(FooStack) end it "should allow me to set a configuration object manually" do config = FooStack::Configuration.new app = FooStack.stackup(:config => config) app.configuration.should equal(config) end it "should allow me to have access to the configuration object when creating the stack through a block" do app = FooStack.stackup do |config| config.foo = :foo config.bar = :bar end app.configuration.foo.should == :foo app.configuration.bar.should == :bar end it "should setup access to the configuration object through Pancakes configuration" do router = FooStack.stackup Pancake.configuration.stacks(FooStack).should be_an_instance_of(FooStack) Pancake.configuration.configs(FooStack).should equal(router.configuration) end it "should allow me to create a configuration with a label" do FooStack.configuration(:my_config).should be_an_instance_of(FooStack::Configuration) FooStack.configuration(:my_config).should_not equal(FooStack.configuration) end it "should create a stack with an app_name" do FooStack.stackup(:app_name => "my.app.name") Pancake.configuration.stacks(FooStack).should be_nil Pancake.configuration.stacks("my.app.name").should be_an_instance_of(FooStack) Pancake.configuration.configs("my.app.name").should be_an_instance_of(FooStack::Configuration) end it "should provide access to the configuration in a block" do Pancake.configuration.configs(FooStack) do |config| config.foo = :foo end @app = FooStack.stackup @app.configuration.foo.should == :foo end end end
hassox/pancake
lib/pancake/middlewares/logger.rb
<reponame>hassox/pancake require 'logger' module Pancake module Middlewares class Logger attr_reader :app def initialize(app) @app = app end def call(env) env[Pancake::Constants::ENV_LOGGER_KEY] ||= Pancake.logger @app.call(env) end end end end
hassox/pancake
lib/pancake/errors.rb
<filename>lib/pancake/errors.rb module Pancake module Errors class HttpError < StandardError extlib_inheritable_accessor :error_name, :code, :description def name; self.class.name; end def code; self.class.code; end alias_method :status, :code def description; self.class.description; end end class NotFound < HttpError self.error_name = "Not Found" self.code = 404 self.description = "The requested resource could not be found but may be available again in the future." end class UnknownRouter < NotFound self.description = "The router could not be found" end class UnknownConfiguration < NotFound self.description = "The configuration could not be found" end class Unauthorized < HttpError self.error_name = "Unauthorized" self.code = 401 self.description = "Authentication is required to access this resource." end class Forbidden < HttpError self.error_name = "Forbidden" self.code = 403 self.description = "Access to this resource is denied." end class Server < HttpError attr_accessor :exceptions self.error_name = "Server Error" self.code = 500 self.description = "An internal server error" def initialize(*args) super @exceptions = [] end end class NotAcceptable < HttpError self.error_name = "Not Acceptable" self.code = 406 self.description = "The requeseted format could not be provided" end end end
hassox/pancake
lib/pancake.rb
require 'rubygems' #require 'hashie' $:.unshift File.join(File.dirname(__FILE__), "pancake", "vendor", "hashie", "lib") require 'hashie' require 'active_support/core_ext/class' require 'active_support/inflector' require 'active_support/core_ext/string/inflections' require 'active_support/ordered_hash' require 'http_router' require 'tilt' module Pancake autoload :Logger, "pancake/logger" autoload :Constants, "pancake/constants" autoload :Console, "pancake/console" autoload :Paths, "pancake/paths" autoload :Configuration, "pancake/configuration" autoload :MimeTypes, "pancake/mime_types" autoload :Middleware, "pancake/middleware" autoload :Router, "pancake/router" autoload :Errors, "pancake/errors" autoload :Stack, "pancake/stack/stack" autoload :PancakeConfig, "pancake/defaults/configuration" module Hooks autoload :OnInherit, 'pancake/hooks/on_inherit' autoload :InheritableInnerClasses, 'pancake/hooks/inheritable_inner_classes' end module Mixins autoload :RequestHelper, "pancake/mixins/request_helper" autoload :Publish, "pancake/mixins/publish" autoload :Render, "pancake/mixins/render" autoload :StackHelper, "pancake/mixins/stack_helper" autoload :ResponseHelper, "pancake/mixins/response_helper" end module Middlewares autoload :Static, "pancake/middlewares/static" autoload :Logger, "pancake/middlewares/logger" end module Test autoload :Matchers, "pancake/test/matchers" autoload :Helpers, "pancake/test/helpers" end end require 'pancake/core_ext/class' require 'pancake/core_ext/object' require 'pancake/core_ext/symbol' require 'pancake/master'
hassox/pancake
lib/pancake/mixins/publish/action_options.rb
module Pancake module Mixins module Publish class ActionOptions attr_reader :params, :formats, :default CONFIG_OPTIONS = [:provides, :only_provides] # Generates a new instance of the class. This instance encapsulates the # options and logic needed to validate the parameters being input into # a controller action. First argument is a list of symbols for the # formats it supports. The second is hash of options. Typically this # hash is generated by the publish declaration in a controller. # # TODO: Allow params to be grouped together # # @api private def initialize(default_formats, opts) # Extract the params — excluding configuration — and turn the keys into # strings. Additionally, check to see if someone has passed in a a raw # value rather than using one of our as_* methods. @params = opts.inject({}) do |memo, opt| unless CONFIG_OPTIONS.include? opt[0] unless opt[1].is_a?(Array) raise "Parameter values must be specified with an as_* method. You passed in a #{opt[1].class.to_s}" end memo[opt[0].to_s] = opt[1] end memo end @formats = extract_format_options(default_formats, opts) end # Accepts a hash of parameters and replaces each entry with it’s # coerced or default value. If an expected param is missing, it will # raise an error. # # TODO: Flag missing params rather than just raising an error # TODO: Allow defaults to be dynamically generated, i.e. method call # # @api private def validate_and_coerce(incoming_params) missing = [] params.each do |name, config| type, default, opts = config value = incoming_params[name] if !value.nil? && value != "" incoming_params[name] = send("validate_and_coerce_#{type}", value, opts) else if default == :req missing << [name, type] elsif default != :opt incoming_params[name] = default end end end [incoming_params, missing] end private # Accepts a string and turns it into an integer. The opts argument is # only there to satisfy the interface. it is not used. # # @api private def validate_and_coerce_integer(value, opts) value.to_i end # Accepts a string and turns it into a date. The opts argument is # only there to satisfy the interface. it is not used. # # @api private def validate_and_coerce_date(value, opts) Date.parse(value) end # Turns the incoming value into a string. The opts argument is # only there to satisfy the interface. it is not used. # # @api private def validate_and_coerce_string(value, opts) value.to_s end # Extracts the format options from a hash. It is used to compile the # list of formats that an action can provide. It accepts an array of # symbols representing the base formats and will add to or overwrite # them based on the options in the hash. # # @api private def extract_format_options(defaults, opts) @formats = if opts[:provides] defaults + [opts[:provides]].flatten elsif opts[:only_provides] [opts[:only_provides]].flatten else defaults end end end # ActionOptions end # Publish end # Mixins end # Pancake
hassox/pancake
lib/pancake/test/helpers.rb
<gh_stars>1-10 module Pancake module Test module Helpers def clear_constants(*classes) classes.flatten.each do |klass| begin Object.class_eval do remove_const klass end rescue => e end end end # clear_constnat3 def env_for(path = "/", opts = {}) Rack::MockRequest.env_for(path, opts) end end # Helpers end end
hassox/pancake
spec/pancake/mime_types_spec.rb
require 'spec_helper' describe Pancake::MimeTypes do before do Pancake::MimeTypes.reset! end it "should have many types" do Pancake::MimeTypes.types.should be_an(Array) end it "should have a type for each mime type defined in Rack::Mime::MIME_TYPES" do Rack::Mime::MIME_TYPES.each do |ext, type| ext =~ /\.(.*)$/ t = Pancake::MimeTypes.type_by_extension($1) t.should_not be_nil t.should be_an_instance_of(Pancake::MimeTypes::Type) t.type_strings.should include(type) end end it "should find the type from an extension" do t = Pancake::MimeTypes.type_by_extension("html") t.should_not be_nil t.type_strings.should include("text/html") end it "should allow me to add a new mime type" do t = Pancake::MimeTypes::Type.new("foo", "text/foobar") type = Pancake::MimeTypes.type_by_extension("foo") type.should_not be_nil type.type_strings.should have(1).item type.type_strings.should include("text/foobar") end describe Pancake::MimeTypes::Type do include Pancake::MimeTypes before do @type = Pancake::MimeTypes::Type.new("html", "text/html") end it "should have one extension" do @type.extension.should == "html" end it "should tell me the type strings" do @type.type_strings.should include("text/html") end it "should allow me to add type strings" do @type.type_strings << "text/foo_html" @type.type_strings.should include("text/foo_html") end it "should not add duplicate type strings" do @type.type_strings.should have(1).item @type.type_strings << "text/html" @type.type_strings.should have(2).items @type.type_strings.should include("text/html") end it "should add non duplicate tpe strying" do @type.type_strings.should have(1).item @type.type_strings << "text/foo_html" @type.type_strings.should have(2).items @type.type_strings.should include("text/foo_html") end end describe "grouping types" do it "should allow me to create a group of mime types" do Pancake::MimeTypes.group(:html).should be_an(Enumerable) end it "should allow me to add mime types to the group" do Pancake::MimeTypes.group_as(:foo, "html", "xhtml") r = Pancake::MimeTypes.group(:foo) r.should have(2).items r.should include(Pancake::MimeTypes.type_by_extension("html")) r.should include(Pancake::MimeTypes.type_by_extension("xhtml")) end it "should allow me to add to a group without creating duplicates" do t = Pancake::MimeTypes::Type.new("foo", "foo/bar") Pancake::MimeTypes.group_as(:bar, "xhtml", "html") Pancake::MimeTypes.group(:bar).should have(2).items Pancake::MimeTypes.group(:bar).should_not include(t) Pancake::MimeTypes.group_as(:bar, "html", "foo", "xhtml") Pancake::MimeTypes.group(:bar).should have(3).items Pancake::MimeTypes.group(:bar).should include(t) end it "should allow me to look up a mime type via a string or symbol identifier" do Pancake::MimeTypes.group(:html).should eql(Pancake::MimeTypes.group("html")) end it "should be empty empty when accessing a non existant mime type" do r = Pancake::MimeTypes.group(:not_a_mime) r.should_not be_nil r.should be_empty r.should respond_to(:each) end it "should populate the group with the types when first acessing when a type with that extension exists" do r = Pancake::MimeTypes.group(:xml) r.should_not be_empty r.each do |t| t.should be_an_instance_of(Pancake::MimeTypes::Type) end end end describe "prepared groups" do it "should prepare the html group" do g = Pancake::MimeTypes.group(:html) g.should have(3).items ["html", "htm", "xhtml"].each do |ext| t = Pancake::MimeTypes.type_by_extension(ext) g.should include(t) end end it "should parepare the text group" do g = Pancake::MimeTypes.group(:text) g.should have(2).items ["text", "txt"].each do |ext| t = Pancake::MimeTypes.type_by_extension(ext) g.should include(t) end end it "should prepare the svg group" do g = Pancake::MimeTypes.group(:svg) g.should have(2).items ["svg", "svgz"].each do |ext| t = Pancake::MimeTypes.type_by_extension(ext) g.should include(t) end end it "should add the text/xml to the xml format" do t = Pancake::MimeTypes.type_by_extension("xml") t.type_strings.should include("text/xml", "application/xml") end end describe "format from accept type" do it "should return the first matching type" do accept_type = "text/plain" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_type, :text) group.should == :text at.should == accept_type r.should_not be_nil r.type_strings.should include("text/plain") end it "should return the first type if the matching type is */*" do accept_type = "*/*;application/xml" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_type, :text, :xml, :html) at.should == "text/plain" group.should == :text r.should_not be_nil r.type_strings.should include("text/plain") end it "should use */* if avaiable" do accept_type = "application/xml,*/*" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_type, :html, :xml) at.should == "text/html" group.should == :html r.should_not be_nil end describe "matching on :any" do it "should use match :any for a request" do accept_type = "text/xml,*/*" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_type, :any) group.should == :any at.should == "text/xml" r.should_not be_nil end it "should match :any for a request with a defualt given" do accept_types = "*/*" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_types, :any, :json) group.should == :any at.should == "application/json" r.should_not be_nil end it "should allow a specified mime type when a default is set" do accept_types = "text/plain" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_types, :any, :json) group.should == :any at.should == "text/plain" r.should_not be_nil end it "should match text/html for a request with only */* with no default" do accept_types = "*/*" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_types, :any) at.should == "text/html" group.should == :any end end it "should return nil if there is no matching class" do accept_type = "text/xml" group, r = Pancake::MimeTypes.negotiate_accept_type(accept_type, :text, :html) r.should be_nil group.should be_nil end it "should return a type when it is not in the first position" do accept_type = "text/xml, text/html,text/plain;" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_type, :svg, :text) group.should == :text r.should_not be_nil r.type_strings.should include("text/plain") r.extension.should == "text" end it "should recognize the type from a quality value" do accept_type = "text/plain;q=0.5,text/html;q=0.8" group, at, r = Pancake::MimeTypes.negotiate_accept_type(accept_type, :text, :html) group.should == :html r.should_not be_nil r.type_strings.should include("text/html") r.extension.should == "html" end end describe "mime from extension" do it "should recognize the mime type from the extension" do group, at, r = Pancake::MimeTypes.negotiate_by_extension("text", :html, :text) group.should == :text at.should == "text/plain" r.should == Pancake::MimeTypes.type_by_extension("text") end it "should recognize grouped mimes by extension" do Pancake::MimeTypes.group_as(:foo, "text", "txt", "html") group, at, r = Pancake::MimeTypes.negotiate_by_extension("txt", :foo) group.should == :foo at.should == "text/plain" r.extension.should == "txt" group, at, r = Pancake::MimeTypes.negotiate_by_extension("text", :foo) r.extension.should == "text" group, at, r = Pancake::MimeTypes.negotiate_by_extension("html", :foo) r.extension.should == "html" at.should == "text/html" end it "should not negotiate by extension when there the extension is not part of the accepted types" do Pancake::MimeTypes.group_as(:bar, "text") group, at, r = Pancake::MimeTypes.negotiate_by_extension("svg", :bar) group.should be_nil at.should be_nil r.should be_nil end it "should negotiate when any by extension" do group, at, r = Pancake::MimeTypes.negotiate_by_extension("xml", :any) group.should == :any at.should == "application/xml" r.should_not be_nil end end end
hassox/pancake
spec/pancake/constants_spec.rb
require 'spec_helper' describe Pancake::Constants do it "should have the ENV_LOGGER_KEY constant" do Pancake::Constants::ENV_LOGGER_KEY.should == "rack.logger" end end
hassox/pancake
spec/pancake/stack/router_spec.rb
<reponame>hassox/pancake require 'spec_helper' describe "stack router" do before(:all) do clear_constants "FooApp" ,"INNER_APP", "BarApp", "InnerApp", "InnerFoo", "InnerBar" end before(:each) do ::INNER_APP = Proc.new{ |e| [ 200, {"Content-Type" => "text/plain"}, [ JSON.generate({ "SCRIPT_NAME" => e["SCRIPT_NAME"], "PATH_INFO" => e["PATH_INFO"], "router.params" => e["router.params"].to_hash }) ] ] } class ::FooApp < Pancake::Stack; end FooApp.roots << Pancake.get_root(__FILE__) end after(:each) do clear_constants "FooApp" ,"INNER_APP", "BarApp" end def app @app end describe "mount" do it "should let me setup routes for the stack" do FooApp.router do |r| r.mount(INNER_APP, "/foo", :default_values => {:action => "foo action"}).name(:foo) r.mount(INNER_APP, "/bar", :default_values => {:action => "bar action"}).name(:root) end @app = FooApp.stackup expected = { "SCRIPT_NAME" => "/foo", "PATH_INFO" => "", "router.params" => {"action" => "foo action"} } get "/foo" JSON.parse(last_response.body).should == expected end it "should allow me to stop the route from partially matching" do FooApp.router do |r| r.mount(INNER_APP, "/foo/bar", :default_values => {:action => "foo/bar"}, :_exact => true).name(:foobar) end @app = FooApp.stackup expected = { "SCRIPT_NAME" => "/foo/bar", "PATH_INFO" => "", "router.params" => {"action" => "foo/bar"} } get "/foo/bar" JSON.parse(last_response.body).should == expected get "/foo" last_response.status.should == 404 end it "should not match a single segment route when only / is defined" do FooApp.router.add("/", :default_values => {:root => :var}) do |e| Rack::Response.new("In the Root").finish end @app = FooApp.stackup result = get "/not_a_route" result.status.should == 404 end describe "mounting stacks" do before do @stack_app = lambda{|e| Rack::Response.new("stacked up").finish} end it "should not imediately stackup the passed in resource" do stack = mock("stack") stack.should_not_receive(:stackup) FooApp.router.mount(stack, "/stackup") end it "should stackup a class if it responds to stackup" do stack = mock("stack") stack.should_receive(:stackup).and_return(@stack_app) FooApp.router.mount(stack, "/stackup") @app = FooApp.stackup result = get "/stackup" result.body.should include("stacked up") end end end describe "generating routes" do before do FooApp.router do |r| r.add("/simple/route" ).name(:simple).compile r.add("/var/with/:var", :default_values => {:var => "some_var"}).name(:defaults).compile r.add("/complex/:var" ).name(:complex).compile r.add("/optional(/:var)" ).name(:optional).compile r.add("/some/:unique_var").compile r.add("/", :default_values => {:var => "root var"}).name(:root).compile end end it "should allow me to generate a named route for a stack" do Pancake.url(FooApp, :simple).should == "/simple/route" end it "should allow me to generate a non-named route for a stack" do Pancake.url(FooApp, :complex, :var => "a_variable").should == "/complex/a_variable" end it "should allow me to generate a route with values" do Pancake.url(FooApp, :optional).should == "/optional" Pancake.url(FooApp, :optional, :var => "some_var").should == "/optional/some_var" end it "should allow me to generate routes with defaults" do Pancake.url(FooApp, :defaults).should == "/var/with/some_var" Pancake.url(FooApp, :defaults, :var => "this_is_a_var").should == "/var/with/this_is_a_var" end it "should generate a base url of '/' for the top level router" do FooApp.router.base_url.should == "/" end describe "mounted route generation" do before do class ::BarApp < Pancake::Stack; end BarApp.roots << Pancake.get_root(__FILE__) BarApp.router do |r| r.add("/simple").name(:simple).compile r.add("/some/:var", :default_values => {:var => "foo"}).name(:foo).compile end FooApp.router.mount(BarApp, "/bar") FooApp.router.mount_applications! FooApp.stackup end it "should allow me to generate a simple nested named route" do Pancake.url(BarApp, :simple).should == "/bar/simple" end it "should allow me to generate a simple nested named route for a named app" do FooApp.router.mount(BarApp, "/different", :_args => [{:app_name => :bar_app}]) FooApp.router.mount_applications! Pancake.url(:bar_app, :simple).should == "/different/simple" Pancake.url(BarApp, :simple).should == "/bar/simple" end it "should generate the base url for a mounted application" do BarApp.configuration.router.base_url.should == "/bar" end it "should generate a base url for a named application" do Pancake.base_url_for(BarApp) end end end describe "internal stack routes" do it "should pass through to the underlying app when adding a route" do FooApp.router.add("/bar", :default_values => {:action => "bar"}).name(:gary).compile class ::FooApp def self.new_endpoint_instance INNER_APP end end FooApp.router.mount(INNER_APP, "/some_mount") @app = FooApp.stackup get "/bar" result = JSON.parse(last_response.body) result["router.params"].should == {"action" => "bar"} end end it "should allow me to inherit routes" do FooApp.router do |r| r.mount(INNER_APP, "/foo(/:stuff)", :default_values => {"originator" => "FooApp"}) end class ::BarApp < FooApp; end BarApp.router do |r| r.mount(INNER_APP, "/bar", :default_values => {"originator" => "BarApp"}) end @app = BarApp.stackup get "/bar" response = JSON.parse(last_response.body) response["router.params"]["originator"].should == "BarApp" get "/foo/thing" response = JSON.parse(last_response.body) response["router.params"]["originator"].should == "FooApp" end it "should generate an inherited route" do FooApp.router do |r| r.add("/simple").name(:simple) r.mount(INNER_APP, "/foo(/:stuff)").name(:stuff) end class ::BarApp < FooApp; end FooApp.router.mount_applications! Pancake.url(BarApp, :simple).should == "/simple" Pancake.url(BarApp, :stuff, :stuff => "that_stuff").should == "/foo/that_stuff" end it "should put the configuration into the env" do FooApp.router.add("/foo").to do |e| e["pancake.request.configuration"].should == Pancake.configuration.configs[FooApp] Rack::Response.new("OK").finish end @app = FooApp.stackup get "/foo" end it "should inherit the router as an inherited inner class" do class ::BarApp < FooApp; end BarApp::Router.should inherit_from(FooApp::Router) end it "should inherit the router class as an inner class" do class ::BarApp < FooApp; end FooApp.router.class.should == FooApp::Router BarApp.router.class.should == BarApp::Router end describe "generating urls inside an application" do before do class ::BarApp < FooApp; end class ::InnerApp attr_reader :env include Pancake::Mixins::RequestHelper def self.app_block(&block) if block_given? @app_block = block end @app_block end def call(env) @env = env instance_eval &self.class.app_block Rack::Response.new("OK").finish end end class ::FooApp; def self.new_app_instance; InnerApp.new; end; end BarApp.router do |r| r.add("/mounted") r.add("/foo").name(:foo) r.add("/other").name(:other) end FooApp.router do |r| r.mount(BarApp, "/bar") r.add( "/foo" ).name(:foo) r.add( "/simple").name(:simple) end @app = FooApp.stackup end it "should generate the urls correctly" do InnerApp.app_block do url(:foo).should == "/foo" url(:simple).should == "/simple" end get "/foo" end it "should generate urls correctly when nested" do InnerApp.app_block do url(:foo).should == "/bar/foo" url(:other).should == "/bar/other" end get "/bar/mounted" end it "should generate a url for another app" do InnerApp.app_block do url_for(BarApp, :foo).should == "/bar/foo" url_for(FooApp, :foo).should == "/foo" end get "/foo" end end end
hassox/pancake
spec/pancake/inheritance_spec.rb
require 'spec_helper' describe "Pancake Inheritance" do describe "on inherit hook" do before(:each) do clear_constants(:MyFoo, :OtherFoo, :FutherFoo, :SomeFoo, :DeeperFoo) class ::MyFoo extend Pancake::Hooks::OnInherit end ::MyFoo.on_inherit do |base, parent| $inherited_capture << {:base => base, :parent => parent} end $inherited_capture = [] end it "should provide on_inherit callbacks" do class ::OtherFoo < MyFoo; end $inherited_capture.should == [{:base => OtherFoo, :parent => MyFoo}] end it "should inherit multiple times" do class ::OtherFoo < MyFoo; end class ::FurtherFoo < OtherFoo; end $inherited_capture.should == [{:base => OtherFoo, :parent => MyFoo}, {:base => FurtherFoo, :parent => OtherFoo}] end it "should allow for multiple callbacks" do MyFoo.on_inherit{|base, parent| $inherited_capture << :second} class ::OtherFoo < MyFoo; end $inherited_capture.should == [{:base => OtherFoo, :parent => MyFoo}, :second] end it "should allow for multiple callbacks that are inherited" do MyFoo.on_inherit{|base, parent| $inherited_capture << :second} class ::OtherFoo < MyFoo; end $inherited_capture = [] OtherFoo.on_inherit{|base, parent| $inherited_capture << :inherited} class ::SomeFoo < OtherFoo; end $inherited_capture.should == [{:base => SomeFoo, :parent => OtherFoo}, :second, :inherited] end it "should not pollute the parent with the child inherited hooks" do class ::OtherFoo < MyFoo; end $inherited_capture = [] OtherFoo.on_inherit{|b,p| $inherited_captuer << :should_not_be_in_there} class ::SomeFoo < MyFoo; end $inherited_capture.should == [{:base => SomeFoo, :parent => MyFoo}] end end # "on inherit hook" describe "inheritable inner classes" do before(:each) do clear_constants(:MyFoo, :OtherFoo, :InnerFoo, :SomeFoo, :DeeperFoo) class ::MyFoo inheritable_inner_classes :InnerFoo class InnerFoo; end end end it "should inherit the inner class along with the outer class" do class ::OtherFoo < MyFoo; end OtherFoo::InnerFoo.superclass.should equal(MyFoo::InnerFoo) OtherFoo::InnerFoo.should_not equal(MyFoo::InnerFoo) end it "should inherit the inner class multiple times" do class ::OtherFoo < MyFoo; end class ::SomeFoo < OtherFoo; end class ::DeeperFoo < SomeFoo; end SomeFoo::InnerFoo.superclass.should equal(OtherFoo::InnerFoo) SomeFoo::InnerFoo.should_not equal(OtherFoo::InnerFoo) DeeperFoo::InnerFoo.superclass.should equal(SomeFoo::InnerFoo) DeeperFoo::InnerFoo.should_not equal(OtherFoo::InnerFoo) DeeperFoo::InnerFoo.superclass.should equal(SomeFoo::InnerFoo) end it "should allow additional inner classes to be declared without polluting the parent" do class ::OtherFoo < MyFoo inheritable_inner_classes :SomeDeepFoo class SomeDeepFoo; end end class ::SomeFoo < MyFoo; end class ::DeeperFoo < ::OtherFoo; end SomeFoo::InnerFoo.should inherit_from(MyFoo::InnerFoo) SomeFoo.const_defined?(:SomeDeepFoo).should be_false DeeperFoo::InnerFoo.should inherit_from(OtherFoo::InnerFoo) DeeperFoo::SomeDeepFoo.should inherit_from(OtherFoo::SomeDeepFoo) end end # "inheritable inner classes" end
hassox/pancake
lib/pancake/hooks/on_inherit.rb
module Pancake module Hooks module OnInherit def self.extended(base) base.class_eval do extlib_inheritable_reader :_on_inherit @_on_inherit = [] end end # Provides an inheritance hook to all extended classes # Allows ou to hook into the inheritance def inherited(base) super _on_inherit.each{|b| b.call(base,self)} end # A hook to add code when the stack is inherited # The code will be executed when the class is inherited # # @example # MyClass.on_inherit do |base, parent| # # do stuff here between the child and parent # end # # @api public # @author <NAME> def on_inherit(&block) _on_inherit << block if block _on_inherit end end # OnInherit end # Hooks end # Pancake
hassox/pancake
lib/pancake/mixins/publish.rb
require File.join(File.dirname(__FILE__), "publish", "action_options") module Pancake module Mixins module Publish def self.extended(base) base.class_eval do extlib_inheritable_accessor :actions, :formats self.actions = {} self.formats = [:html] end end # Accepts a list of symbols representing the formats each action in the # controller will return. By default the list consists only of :html # # provides :html, :xml # # @api public def provides(*args) self.formats = args end # Causes the next method added immediately after it’s call to be defined # as an action. It also generates an instance of ActionOptions, which # encapsulates all the parameters the action accepts/expects and also # the formats that it can potentially return. # # publish :id => as_integer(:req) # def show # ... # end # # The example above publishes the action "show" and configures the # following options for it: # # - The parameter 'id' will be coerced into an Integer # - It also must not be blank, it is required. # # The publish declaration can also create much more sophisticated # constraints. You can declare a parameter as optional, give it a default # value if it is missing. # # Here, 'start' and 'end' are required — the default — and are coerced into # date values. The 'page' parameter is optional, with the default being 1. # # publish :start => as_date, :end => as_date :page => as_integer(1) # # For a list of the built in coercions look in the API for methods prefixed # with 'as_'. These are intended to be used in your publish declarations. # # #publish can also handle the specification of formats for an action. It # accepts an additional two options, :provides and :only_provides. # # To the list of globally declared formats, :provides adds additional # formats to an action. # # publish :provides => :xml # # The :only_provides option overrides any globally declared formats for an # action. # # publish :only_provides => [:json, :xml] # # @api public def publish(opts = {}) @pending_publication_opts = opts end # Used when declaring configuration for parameters in the publish # declaration. It returns an array of the type, default value an # additional options. # # @param type [Object] The # # The current supported types are # - :integer # - :date # - :string # # For details on the options supported by each type, please see the # corresponding methods declared in the ActionOptions class. These methods # are named as the type, prefixed with 'validate_and_coerce_' # # # @example # Here is an example where we declare an integer and that it is required # # as(:integer, :req) # # Or that it is optional, but has a default value if it is missing. # # as(:integer, 21) # # @api public def as(type, default = :req, opts = {}) [type, default, opts] end # Takes a parameters hash, and validates each entry against the options # defined for this action. It will flag required params when missing, # insert defaults or coerce values into the desired type. It mutates # the params hash itself. # # @api private def validate_and_coerce_params(action, params) actions[action].validate_and_coerce(params) end # This hook is used in conjunction with the #publish method to expose # instance methods as actions. Obviously, it should never be called # directly :) # # @api private def method_added(name) super if @pending_publication_opts self.actions[name.to_s] = ActionOptions.new(formats, @pending_publication_opts) @pending_publication_opts = nil end end end # Publish end # Mixins end # Pancake
hassox/pancake
spec/pancake/mixins/publish_spec.rb
<gh_stars>1-10 require 'spec_helper' describe "Pancake::Controller publish declaration" do before(:each) do class ::PancakeTest extend Pancake::Mixins::Publish provides :html publish def simple_publish; end publish :id => as(:integer) def integer_test; end publish :start => as(:date) def date_test; end publish :page => as(:integer, 12) def default_test; end publish :provides => [:xml, :json] def provides_test; end publish :only_provides => :xml def only_provides_test; end publish :name => as(:string, :opt) def optional_test; end publish :provides => [:json, :txt], :id => as(:integer, :req), :name => as(:string, "Campion"), :melon => as(:integer, 50), :jam => as(:string, :opt), :squeeze => as(:string, :req) def complex_test; end end end after do clear_constants "PancakeTest" end it "should publish an action" do PancakeTest.actions['simple_publish'].is_a?(Pancake::Mixins::Publish::ActionOptions).should == true end it "should coerce a parameter into an integer" do params, missing = PancakeTest.__send__(:validate_and_coerce_params, 'integer_test', 'id' => "30") params['id'].should == 30 end it "should coerce a parameter into a date" do date = Date.parse("2009/07/05") params, missing = PancakeTest.__send__(:validate_and_coerce_params, 'date_test', 'start' => "2009/07/05") params['start'].should == date end it "should flag required params that are missing" do params, missing = PancakeTest.__send__(:validate_and_coerce_params, 'integer_test', {}) missing.include?(['id', :integer]).should == true end it "should allow parameters to be optional" do params, missing = PancakeTest.__send__(:validate_and_coerce_params, 'optional_test', {}) missing.empty?.should == true end it "should return a default value for a parameter" do params, missing = PancakeTest.__send__(:validate_and_coerce_params, 'default_test', {}) params['page'].should == 12 end it "should append formats to the list allowed for an action" do PancakeTest.actions['provides_test'].formats.should == [:html, :xml, :json] end it "should replace the list of formats allowed for an action" do PancakeTest.actions['only_provides_test'].formats.should == [:xml] end it "should allow complex declarations" do input = {'id' => "30", 'name' => "Purslane"} params, missing = PancakeTest.__send__(:validate_and_coerce_params, 'complex_test', input) params['id'].should == 30 params['name'].should == "Purslane" params['melon'].should == 50 params['jame'].should be_nil missing.include?(['squeeze', :string]).should == true PancakeTest.actions['complex_test'].formats.should == [:html, :json, :txt] end end
hassox/pancake
pancake.gemspec
# -*- encoding: utf-8 -*- require 'bundler' Gem::Specification.new do |s| s.name = 'pancake' s.version = File.read('VERSION') s.homepage = %q{http://github.com/hassox/pancake} s.authors = ["<NAME>"] s.autorequire = %q{pancake} s.date = Date.today s.default_executable = %q{pancake} s.description = %q{Eat Pancake Stacks for Breakfast} s.email = %q{<EMAIL>} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.executables = ["pancake"] s.rubygems_version = %q{1.3.6} s.summary = %q{Eat Pancake Stacks for Breakfast} s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.extra_rdoc_files = [ "LICENSE", "README.textile", "TODO.textile" ] s.files = %w(LICENSE README.textile Rakefile TODO.textile) + Dir.glob("{lib,spec,bin}/**/{*,.[a-z]*}") s.add_bundler_dependencies end
hassox/pancake
lib/pancake/master.rb
<filename>lib/pancake/master.rb module Pancake # A simple rack application OK_APP = lambda{|env| Rack::Response.new("OK", 200, {"Content-Type" => "text/plain"}).finish} MISSING_APP = lambda{|env| Rack::Response.new("NOT FOUND", 404, {"Content-Type" => "text/plain"}).finish} extend Middleware class << self attr_accessor :root attr_accessor :_before_build, :_generators def before_build(&blk) unless _before_build self._before_build = [] end _before_build << blk if blk _before_build end def generators(&blk) self._generators = [] unless _generators _generators << blk if blk _generators end def load_generators! return if @load_generators @load_generators = true generators.each{|b| b.call} # load any global generator files highest = {} Gem.find_files("pancake/generators/global.rb").sort.reverse.each do |f| f =~ /gems\/([^\/]+?)-(\d\.[^\/]+?)\/lib\/pancake/ highest[$1] ||= begin require f f end end end # Start Pancake. This provides a full pancake stack to use inside a rack application # # @param [Hash] opts # @option opts [String] :root The root of the pancake stack # # @example Starting a pancake stack # Pancake.start(:root => "/path/to/root"){ MyApp # App to use} # # @api public # @author <NAME> def start(opts = {}, &block) self.root = opts[:root] || Dir.pwd # Build Pancake the_app = instance_eval(&block) before_build.each{|blk| blk.call} Pancake::Middleware.build(the_app, middlewares) end # Provides the environment for the currently running pancake # # @return [String] The currently running environment # @api public # @author <NAME> def env ENV['RACK_ENV'] ||= "development" end # A helper method to get the expanded directory name of a __FILE__ # # @return [String] an expanded version of file # @api public # @author <NAME> def get_root(file, *args) File.expand_path(File.join(File.dirname(file), *args)) end def handle_errors!(*args) @handle_errors = begin if args.size > 1 args.flatten else args.first end end end def handle_errors? if @handle_errors.nil? !(Pancake.env == "development") else case @handle_errors when Array @handle_errors.include?(Pancake.env) when TrueClass, FalseClass @handle_errors when String Pancake.env == @handle_errors end end end def default_error_handling! @handle_errors = nil end def logger @logger ||= Pancake::Logger.new end def logger=(logr) @logger = logr end # The stack to use as the master stack. Can be nil! # The master stack is assumed to be the stack that is the controlling stack for the group of pancake stacks # @api public def master_stack @master_stack end # set the master stack. This also sets the master_templates as this stack if that hasn't yet been set. # @see Pancake.master_templates # @api public def master_stack=(stack) self.master_templates ||= stack @master_stack = stack end # Used as the definitive source of shared templates for the whole pancake graph. # Allows different stacks to share the same templates # @see Pancake.master_templates= # @api public def master_templates @master_templates end # Set the master templates to control the default templates for the stack # @see Pancake.master_templates # @api public def master_templates=(stack) @master_templates = stack end # provides access to the default base template via the Pancake.master_templates object # @see Pancake.master_templates # @api public def default_base_template(opts = {}) raise "Master Templates not set" unless master_templates master_templates.template(master_templates.base_template_name) end end # self end # Pancake
hassox/pancake
lib/pancake/configuration.rb
<gh_stars>1-10 module Pancake class Configuration class Base extlib_inheritable_reader :defaults @defaults = Hash.new{|h,k| h[k] = {:value => nil, :description => ""}} # Set a default on the the configuartion class << self # Set a default for this configuration class # Provide a field/method name and a value to set this to. # If you don't provide a value, and instead provide a block, then # a proc will be called lazily when requested. # # Example # config_klass = Pancake::Configuration.make # config_class.default :foo, :bar, "This foo is a bar" # config = config_class.new # # :api: public def default(meth, *args, &block) value, description = args if block description = value value = block end defaults[meth][:value] = value defaults[meth][:description] = description || "" end # Provides aaccess to the description for a default setting # # :api: public def description_for(field) defaults.keys.include?(field) ? defaults[field][:description] : "" end end # access to the singleton class # :api: private def singleton_class # :nodoc: class << self; self; end end # Access to the configuration defaults via the instance. Defers to the # clas smethod for defaults # :api: public def defaults self.class.defaults end # Access to the class descritpion for defaults # :api: public def description_for(field) self.class.description_for(field) end # Access to the currently set values for this configuration object # :api: public def values @values ||= {} end private def method_missing(name, *args) if name.to_s =~ /(.*?)=$/ set_actual_value($1.to_sym, args.first) else if defaults.keys.include?(name) # We don't want to trigger a default value if we're blindly setting it # If the default is a proc, do not cache it case defaults[name][:value] when Proc p = defaults[name][:value] instance_eval &p else val = defaults[name][:value] val = val.dup rescue val set_actual_value(name, val) end else nil end end end # Caches the values via a method rather than going through method_missing # :api: private def set_actual_value(name, val) # :nodoc: singleton_class.class_eval <<-RUBY def #{name}=(val) # def foo=(val) values[#{name.inspect}] = val # values[:foo] = val end # end def #{name} # def foo values[#{name.inspect}] # values[:foo] end # end RUBY values[name] = val end end # Base class << self # Make a new configuration class # :api: public def make(&block) Class.new(Pancake::Configuration::Base, &block) end end # self end # Configuration def self.configuration @configuration ||= PancakeConfig.new end def self.reset_configuration @configuration = nil end end # Pancake
hassox/pancake
lib/pancake/mime_types.rb
<gh_stars>1-10 require 'set' require 'rack/accept_media_types' module Pancake module MimeTypes # A collection of all the mime types that pancake knows about # # @returns [Array<Pancake::MimeTypes::Type>] an array of # Pancake::MimeTypes::Type objects that pancake knows about. To # add a new type to the collection, simply create a new # Pancake::MimeTypes::Type # # @see Pancake::MimeTypes::Type # @api public # @author <NAME> def self.types @types || reset! && @types end # Finds a Pancake::MimeTypes::Type object by the provided # extension # # @param ext [String,Symbol] - The extension to look for # @return [Pancake::MimeTypes::Type, nil] - The corresponding mime # type object or nil if there were none found that match the # provided extension # # @example # Pancake::MimeTypes.type_by_extension("html") # => A # Pancake::MimeTypes::Type object for the .html extension # # @see Pancake::MimeTypes::Type # @api public # @author <NAME> def self.type_by_extension(ext) ext = ext.to_s types.detect{|t| t.extension == ext} end # Pancake manages mime types by grouping them together. # # @return [Set<Pancake::MimeTypes::Type>] - A enumerable of Type # objects associated with this group # # @see Pancake::MimeTypes.group # @api public # @author <NAME> def self.groups @groups || reset! && @groups end # Pancake::MimeTypes are managed by grouping them together. # Each group may consist of many mime types by extension # By Accessing a group that doesn't yet exist, the group is # created and initialized with the matching type with extension # A group may have many mime type / accept types associated with # it # # @param name [String,Symbol] - The name of the group # # @example # Pancake::MimeTypes.group(:html) # # @return [Enumerable<Pancake::MimeTypes::Type>] - returns all # mime types in the specified group. If the group does not exist, # or has not been accessed, the group will be created on the fly # with the first mime type that matches the group name # # @see Pancake::MimeTypes.group_as # @api public # @author <NAME> def self.group(name) groups[name.to_s] end # Creates a group of mime types. Any group of mimes can be # arbitrarily grouped under the specified name. The group is # initilized with the mime type whose extension matches the name, # and any further extensions have their mime types added to the # group # # @param name [String,Symbol] - the name of the group to # create/append # @param exts [List of String,Symbol] - a list of extensions to # associate with this mime type # # @see Pancake::MimeTypes.group # @api public # @author <NAME> def self.group_as(name, *exts) exts.each do |ext| group(name) << type_by_extension(ext) unless group(name).include?(type_by_extension(ext)) end group(name) end # Resets the Pancake::MimeType cache and re-creates the # Pancake::MimeTypes default types and groups # Good for use in specs # @api private def self.reset! @types = [] @negotiated_accept_types = nil @groups = Hash.new do |h,k| k = k.to_s h[k] = [] t = Pancake::MimeTypes.type_by_extension(k) h[k] << t unless t.nil? h[k] end reset_mime_types! reset_mime_groups! end # Used in specs to reset the mime types back to their # corresponding originals in Rack::Mime::MIME_TYPES # @api private def self.reset_mime_types! # Setup the mime types based on the rack mime types Type.new("any") Rack::Mime::MIME_TYPES.each do |ext, type| ext =~ /\.(.*)$/ e = $1 t = type_by_extension(ext) if t t.type_strings << type else t = Type.new(e, type) end end end # Used in specs to reset the default mime groups of # pancake::MimeTypes # @api private def self.reset_mime_groups! # html group_as(:html, "html", "htm", "xhtml") group_as(:text, "text", "txt") type_by_extension("xml").type_strings << "text/xml" group_as(:svg, "svgz") end # Negotiates the type and group that the accept_type string # matches # @param type [String] the accept_type header string from the # request # @param provided [list of String,Symbol] - A list of strings / # symbols of the included groups to use to try and match this # accept type header. # # @example # accept_type = "text/xml,text/html" # result = Pancake::MimeTypes.negotiate_accept_type(accept_type, :html, # :text) # result # => [:html, <#Pancake::MimeTypes::Type for html>] # # @return [Array] An array with the group name, and mime type # @api public # @author <NAME> def self.negotiate_accept_type(type, *provided) accepted_types = Rack::AcceptMediaTypes.new(type) provided = provided.flatten key = [accepted_types, provided] return negotiated_accept_types[key] if negotiated_accept_types[key] accepted_type = nil if accepted_types.include?("*/*") if provided.include?(:any) name = :any if at = accepted_types.detect{|t| t != "*/*"} at elsif t = provided.detect{|a| a != :any} at = group(t).first.type_strings.first else at = "text/html" end else name = provided.first accepted_type = group(name).first at = accepted_type.type_strings.first end accepted_type = group(name).first negotiated_accept_types[key] = [name, at, accepted_type] return negotiated_accept_types[key] end # Check to see if any accepted types match accepted_types.each do |at| provided.flatten.each do |name| accepted_type = match_content_type(at, name) if accepted_type if name == :any if at = accepted_types.detect{|a| a != "*/*"} return [name, at, accepted_type] elsif at = provided.flatten.detect{|p| p != :any} return [name, at.type_strings.first, accepted_type] else return [name, "text/html", accept_type] end end at = accepted_type.type_strings.first if at == "*/*" if accepted_types.join.size > 4096 # Don't save the key if it's larger than 4 k. # This could hit a dos attack if it's repeatedly hit # with anything large negotiated_accept_types[key] = [name, at, accepted_type] end return [name, at, accepted_type] end end end nil end # Negotiates the content type based on the extension and the # provided groups to see if there is a match. # # @param ext [String] The extension to negotiate # @param provided [Symbol] A list of symbols each of which is the # name of a mime group # # @return [Symbol, String, Pancake::MimeTypes::Type] The first # parameter returned is the group name that matched. The second, # is the Content-Type to respond to the client with, the third, # the raw pancake mime type # # @see Pancake::MimeTypes.group # @see Pancake::MimeTypes::Type # @api public def self.negotiate_by_extension(ext, *provided) provided = provided.flatten key = [ext, provided] return negotiated_accept_types[key] if negotiated_accept_types[key] result = nil provided.each do |name| if name == :any at = group(ext.to_sym).first return nil if at.nil? result = [name, at.type_strings.first, at] negotiated_accept_types[key] = result return result end group(name).each do |type| if type.extension == ext result = [name, type.type_strings.first, type] negotiated_accept_types[key] = result return result end end end result end # self.negotiate_by_extension # A basic type for mime types # Each type can have an extension and many type strings that # correspond to the mime type that would be specified in a request # When a Pancake::MimeTypes::Type is created, it is added to the # Pancake::MimeTypes.types collection # @api public class Type attr_reader :type_strings, :extension def initialize(extension, *type_strings) @extension = extension @type_strings = [] type_strings.flatten.each do |ts| @type_strings << ts end MimeTypes.types << self end end private # Checks to see if a group matches an accept type string # @api private def self.match_content_type(accept_type, key) group(key).detect do |t| if key == :any true else t.type_strings.include?(accept_type) || accept_type == "*/*" end end end # Provides a cache for already negotiated types # @api private def self.negotiated_accept_types @negotiated_accept_types ||= {} end end # MimeTypes end # Pancake
hassox/pancake
spec/pancake/fixtures/tasks/root1/tasks/task2.rake
$captures << "root1/tasks/task2.rake"
hassox/pancake
spec/pancake/paths_spec.rb
<reponame>hassox/pancake require 'spec_helper' describe Pancake::Paths do def fixture_root File.expand_path(File.join(File.dirname(__FILE__), "fixtures", "paths")) end before(:each) do remove_consts! class ::Foo extend Pancake::Paths end end after(:all) do remove_consts! end def remove_consts! Object.class_eval do remove_const("Foo") if defined?(Foo) remove_const("Bar") if defined?(Bar) remove_const("Baz") if defined?(Baz) end end describe "setting roots" do it "should allow me to set roots" do Foo.roots.should == [] Foo.roots << fixture_root Foo.roots.should == [fixture_root] end end describe "pushing paths" do before do Foo.roots << fixture_root end it "should push a single path" do Foo.push_paths(:models, "models") Foo.dirs_for(:models).should == [File.join(fixture_root,"models")] end it "should give me an empty array of paths when there have been no paths added" do Foo.dirs_for(:models).should == [] end it "should raise and error if there are no paths specified" do lambda do Foo.push_paths(:models) end.should raise_error(ArgumentError) lambda do Foo.push_paths(:models, []) end.should raise_error(Pancake::Paths::NoPathsGiven) end it "should allow me to push multiple times to a single path group" do Foo.push_paths(:models, "models") Foo.push_paths(:models, "stack/models") Foo.dirs_for(:models).should == [ File.join(fixture_root, "models"), File.join(fixture_root, "stack", "models") ] end it "should allow me to push multiple path sets" do Foo.push_paths(:models, ["models", "stack/models"]) Foo.push_paths(:controllers, "controllers") Foo.push_paths(:views, "stack/views") Foo.dirs_for(:models).should == [ File.join(fixture_root, "models"), File.join(fixture_root, "stack", "models") ] Foo.dirs_for(:controllers ).should == [File.join(fixture_root, "controllers")] Foo.dirs_for(:views ).should == [File.join(fixture_root, "stack", "views")] end it "should reverse the dirs_for when specified" do Foo.push_paths(:models, ["models", "stack/models"]) Foo.dirs_for(:models, :invert => true).should == [ File.join(fixture_root, "stack", "models"), File.join(fixture_root, "models") ] end describe "globs" do it "should allow me to supply a glob to associate with the path" do Foo.push_paths(:models, "models", "**/*.rb") Foo.push_paths(:models, "stack/models", "**/*.rb") Foo.dirs_and_glob_for(:models).should == [ [File.join(fixture_root, "models"), "**/*.rb"], [File.join(fixture_root, "stack", "models"), "**/*.rb"] ] end it "should associate an empty glob when not specified" do Foo.push_paths(:models, "foo/bar") Foo.dirs_for(:models).should == [File.join(fixture_root, "foo/bar")] Foo.dirs_and_glob_for(:models).should == [[File.join(fixture_root, "foo/bar"), nil]] end it "should revers the dirs_and_globs when requested" do Foo.push_paths(:models, "models", "**/*.rb") Foo.push_paths(:models, "stack/models", "**/*.rb") result = Foo.dirs_and_glob_for(:models, :invert => true) result.should == [ [File.join(fixture_root, "stack", "models"), "**/*.rb"], [File.join(fixture_root, "models"), "**/*.rb"] ] end end end describe "reading paths" do before(:each) do @model_root = File.join(fixture_root, "models") @stack_root = File.join(fixture_root, "stack/models") Foo.roots << fixture_root Foo.push_paths(:model, ["models", "stack/models"], "**/*.rb") end it "should have list all the paths for :model" do result = Foo.paths_for(:model).should == [ [@model_root, "/model1.rb"], [@model_root, "/model2.rb"], [@model_root, "/model3.rb"], [@stack_root, "/model3.rb"] ] end it "should allow me to invert the order of the roots" do result = Foo.paths_for(:model, :invert => true).should == [ [@stack_root, "/model3.rb"], [@model_root, "/model3.rb"], [@model_root, "/model2.rb"], [@model_root, "/model1.rb"] ] end it "should allow me to get the unique_paths" do result = Foo.unique_paths_for(:model).should == [ [@model_root, "/model1.rb"], [@model_root, "/model2.rb"], [@stack_root, "/model3.rb"] ] end it "should allow me to invert the order of the unique_paths" do result = Foo.unique_paths_for(:model, :invert => true).should == [ [@model_root, "/model3.rb"], [@model_root, "/model2.rb"], [@model_root, "/model1.rb"] ] end end describe "inherited paths" do before(:each) do Foo.push_paths(:model, "models") Foo.push_paths(:controller, "controllers") Foo.roots << fixture_root class ::Bar < Foo; end end it "should inherit paths from the parent" do Bar.dirs_for(:model).should == [File.join(fixture_root, "models")] Bar.dirs_for(:controller).should == [File.join(fixture_root, "controllers")] end it "should let me add to the collection from the parent" do Bar.push_paths(:model, "stack/models") Bar.dirs_for(:model).should == [ File.join(fixture_root, "models"), File.join(fixture_root, "stack/models") ] end it "should not bleed paths back up to the parent" do Bar.push_paths(:model, "stack/models") Foo.dirs_for(:model).should == [File.join(fixture_root, "models")] end it "should not bleed paths over to a sibling class" do class ::Baz < Foo; end Bar.push_paths(:model, "stack/models") Baz.push_paths(:model, "baz/paths") Bar.dirs_for(:model).should == [ File.join(fixture_root, "models"), File.join(fixture_root, "stack/models") ] Baz.dirs_for(:model).should == [ File.join(fixture_root, "models"), File.join(fixture_root, "baz/paths") ] Foo.dirs_for(:model).should == [File.join(fixture_root, "models")] end it "should inherit multpile times" do class ::Baz < Bar; end Bar.push_paths(:model, "bar/path") Baz.dirs_for(:model).should == [ File.join(fixture_root, "models"), File.join(fixture_root, "bar/path") ] end end end
hassox/pancake
spec/pancake/mixins/render_spec.rb
require 'spec_helper' describe Pancake::Mixins::Render do before do class ::RenderSpecClass include Pancake::Mixins::Render # setup the renderer roots << File.expand_path(File.join(File.dirname(__FILE__), "..", "fixtures", "render_templates")) push_paths :views, "/", "**/*" def self._template_name_for(name, opts = {}) opts[:format] ||= :html "#{name}.#{opts[:format]}" end def params @params ||= {} end def string render :text => "A String" end def the_current_context "the current context" end end unless defined?(AnotherRenderSpecClass) class ::AnotherRenderSpecClass < RenderSpecClass def self._template_name_for(name, opts = {}) opts[:format] ||= :html names = [] names << "#{name}.#{ENV['RACK_ENV']}.#{opts[:format]}" if ENV['RACK_ENV'] names << "#{name}.#{opts[:format]}" names end end end @render = RenderSpecClass.new end after do clear_constants "RenderSpecClass" end it "should allow me to render a string" do @render.string.should == "A String" end it "should render a haml" do @render.render(:haml_template).chomp.should == "IN HAML" end it "should provide me with a template from the class" do template = RenderSpecClass.template(:haml_template) template.should be_a_kind_of(Pancake::Mixins::Render::Template) end it "should allow me to set the format for a given template" do template = RenderSpecClass.template(:erb_template, :format => :json) template.should be_a_kind_of(Pancake::Mixins::Render::Template) template.name.should == "erb_template.json" end it "should render erb" do @render.render(:erb_template).should == "IN ERB" end it "should render an xml format" do @render.render(:haml_template, :format => :xml).chomp.should == "IN HAML XML" end it "should render an erb template for json" do @render.render(:erb_template, :format => :json).chomp.should == "IN ERB JSON" end it "should render with the rendering controller as the current context" do @render.render(:context_template) $captures.first.should be_a_kind_of(Pancake::Mixins::Render::ViewContext) end it "should yield v when rendering" do mock_v = {} mock_v.should_receive(:in_the_block) @render.should_receive(:v).and_return(mock_v) @render.render(:haml_template) do |v| v.should be_a_kind_of(Hash) v.in_the_block end end it "should render the first avaibale template with the rack env set" do begin orig_env = ENV['RACK_ENV'] ENV['RACK_ENV'] = 'foo_env' renderer = AnotherRenderSpecClass.new template = AnotherRenderSpecClass.template(:alternate) template.name.should == "alternate.foo_env.html" response = renderer.render(:alternate) response.should include("In alternate.foo_env.html") ensure ENV['RACK_ENV'] = orig_env end end it "should render the correct template with the rack env set" do begin orig_env = ENV['RACK_ENV'] ENV['RACK_ENV'] = nil renderer = AnotherRenderSpecClass.new template = AnotherRenderSpecClass.template(:alternate) template.name.should == "alternate.html" response = renderer.render(:alternate) response.should include("In alternate.html") ensure ENV['RACK_ENV'] = orig_env end end end
hassox/pancake
spec/pancake/fixtures/tasks/root1/tasks/task1.rake
$captures << "root1/tasks/task1.rake"
hassox/pancake
lib/pancake/mixins/stack_helper.rb
<filename>lib/pancake/mixins/stack_helper.rb module Pancake module Mixins module StackHelper def self.included(base) base.extlib_inheritable_accessor :_stack_class base.extend ClassMethods base.class_eval do include ::Pancake::Mixins::StackHelper::InstanceMethods end base.stack_class end module ClassMethods def stack_class return @_stack_class if @_stack_class klass = nil if name =~ /^\#<Class/ raise "Could not determine the stack. Make sure you declare global classes with a preceeding ::" end ns = name.split("::") until ns.empty? || klass r = ActiveSupport::Inflector.constantize(ns.join("::")) if r.ancestors.include?(::Pancake::Stack) klass = r else ns.pop end end if klass.nil? raise "#{name} is not from a stack" unless _stack_class else self._stack_class = r end _stack_class end end module InstanceMethods def stack_class self.class.stack_class end end end # StackHelper end # Mixins end # Pancake
hassox/pancake
spec/pancake/hooks/on_inherit_spec.rb
require 'spec_helper' describe "Pancake::Stack inheritance" do describe "inheritance hooks" do before(:all) do $on_inherit_blocks = Pancake::Stack.on_inherit.dup end after(:all) do Pancake::Stack.on_inherit.clear $on_inherit_blocks.each do |blk| Pancake::Stack.on_inherit(&blk) end end before(:each) do $collector = [] clear_constants(:FooStack) Pancake::Stack.on_inherit.clear end after(:each) do clear_constants(:FooStack) end it "should be able to add inheritance hooks" do Pancake::Stack.on_inherit do |base, parent| $collector << base end class ::FooStack < Pancake::Stack; end $collector.should == [FooStack] end it "should be able to add multiple inheritance hooks" do Pancake::Stack.on_inherit{|b,p| $collector << b} Pancake::Stack.on_inherit{|b,p| $collector << :foo} class ::FooStack < Pancake::Stack end $collector.should == [FooStack, :foo] end end describe "Inheriting Stacks" do before(:all) do clear_constants(:FooStack, :BarStack) end before(:each) do class ::FooStack < Pancake::Stack; end end after(:each) do clear_constants(:FooStack, :BarStack) end describe "configuration" do it "should inherit the configuration with a stack" do class ::BarStack < ::FooStack; end BarStack::Configuration.should inherit_from(FooStack::Configuration) end end end end
hassox/pancake
lib/pancake/test/matchers.rb
module Pancake module Test module Matchers class MountMatcher def initialize(expected_app, path) @expected_app, @path = expected_app, path end def matches?(target) @target = target @ma = @target::Router.mounted_applications.detect{|m| m.mounted_app == @expected_app} if @ma @ma.mounted_app == @expected_app && @ma.mount_path == @path else false end end def failure_message_for_should if @ma "Expected #{@target} to mount #{@expected_app} at #{@path.inspect} but was mounted at #{@ma.mount_path.inspect}" else "Expected #{@target} to mount #{@expected_app} but it was not mounted" end end def failure_message_for_should_not if @ma "Expected #{@target} to not implement #{@expected_app} at #{@path} but it was mounted there" end end end # MountMatcher def mount(expected, path) MountMatcher.new(expected, path) end class InheritFrom def initialize(expected) @expected = expected end def matches?(target) @target = target @target.ancestors.include?(@expected) end def failure_message "expected #{@target} to inherit from #{@expected} but did not" end end def inherit_from(expected) InheritFrom.new(expected) end end # Matchers end # Test end # Pancake
hassox/pancake
spec/pancake/pancake_spec.rb
require 'spec_helper' describe "pancake" do it "should get the correct root directory for a file" do Pancake.get_root(__FILE__).should == File.expand_path(File.dirname(__FILE__)) end it "should join the arguments together to form a path" do Pancake.get_root(__FILE__, "foo").should == File.expand_path(File.join(File.dirname(__FILE__), "foo")) end describe "handle errors" do before do @orig_env = ENV['RACK_ENV'] end after do ENV['RACK_ENV'] = @orig_env end it "should allow me to set the error handling status to true" do Pancake.handle_errors!(true) Pancake.handle_errors?.should be_true end it "should allow me to set the error handling status to a false" do Pancake.handle_errors!(false) Pancake.handle_errors?.should be_false end it "should allow me to set the error handling status to a value" do Pancake.handle_errors!("some_string") ENV['RACK_ENV'] = "some_string" Pancake.handle_errors?.should be_true ENV['RACK_ENV'] = "other string" Pancake.handle_errors?.should be_false end it "should allow me to set the error handling status to an array of strings" do Pancake.handle_errors!("some", "another") ENV['RACK_ENV'] = "some" Pancake.handle_errors?.should be_true ENV['RACK_ENV'] = "another" Pancake.handle_errors?.should be_true ENV['RACK_ENV'] = "different" Pancake.handle_errors?.should be_false end it "should default to handling errors in production" do Pancake.default_error_handling! ENV['RACK_ENV'] = "production" Pancake.handle_errors?.should be_true end it "should default to not handling errors in development" do Pancake.default_error_handling! ENV['RACK_ENV'] = "development" Pancake.default_error_handling! end it "should default to handling errors in test" do Pancake.default_error_handling! ENV['RACK_ENV'] = "test" Pancake.default_error_handling! end end describe "master stack" do before do @b4 = Pancake.master_stack @tb4 = Pancake.master_templates end after do Pancake.master_stack = @b4 Pancake.master_templates = @tb4 end it "should have a master stack" do Pancake.should respond_to(:master_stack) end it "should let me set a master stack" do mock_stack = mock("stack", :null_object => true) Pancake.master_stack = mock_stack Pancake.master_stack.should == mock_stack end it "should provide master templates stack as the master stack" do mock_stack = mock("stack", :null_object => true) Pancake.master_stack = mock_stack Pancake.master_templates.should == mock_stack end it "should let me overwrite the master_templates independantly of the master" do mock_stack = mock("stack", :null_object => true) mock_ui = mock("ui stack", :null_object => true) Pancake.master_stack = mock_stack Pancake.master_templates = mock_ui Pancake.master_templates.should == mock_ui Pancake.master_stack.should == mock_stack end it "should not change the master templates when updating the master" do stack1 = mock("stack1", :null_object => true) ui = mock("ui", :null_object => true) Pancake.master_templates = ui Pancake.master_stack = stack1 end it "should provide me with the default template from the master_templates" do ui = mock("ui") ui.should_receive(:base_template_name).and_return(:fred) ui.should_receive(:template).with(:fred).and_return(:template_fred) Pancake.master_templates = ui Pancake.default_base_template.should == :template_fred end end end
hassox/pancake
lib/pancake/stack/stack.rb
<reponame>hassox/pancake<filename>lib/pancake/stack/stack.rb module Pancake class Stack attr_accessor :app_name class_inheritable_array :_after_stack_initialize, :_after_build_stack, :_before_build_stack self._after_stack_initialize = [] self._after_build_stack = [] self._before_build_stack = [] # extend Hooks::InheritableInnerClasses extend Hooks::OnInherit extend Pancake::Middleware extend Pancake::Paths # Push the default paths in for this stack push_paths(:config, "config", "config.rb") push_paths(:config, "config/environments", "#{Pancake.env}.rb") push_paths(:rake_tasks, "tasks", "**/*.rake") push_paths(:public, "public", "**/*") push_paths(:mounts, "mounts", "*/pancake_init.rb") push_paths(:middlewares, "config/middlewares", "**/*.rb") #Iterates the list of roots in the stack, and initializes the app found their def self.initialize_stack(opts = {}) raise "Stack root not set" if roots.empty? master = opts.delete(:master) set_as_master! if master paths_for(:config ).each{ |f| require f.join } paths_for(:mounts ).each{ |f| require f.join } paths_for(:middleware ).each{ |f| require f.join } router.mount_applications! set_as_master! if master @initialized = true # run the hook for after mounting after_stack_initialize.each{ |blk| blk.call(self) } end # initiailze stack def self.after_stack_initialize(&blk) _after_stack_initialize << blk if blk _after_stack_initialize end def self.after_build_stack(&blk) _after_build_stack << blk if blk _after_build_stack end def self.before_build_stack(&blk) _before_build_stack << blk if blk _before_build_stack end # Adds the file to the stack root. # # @param file - The file identifier # @example # MyStack.add_root(__FILE__) # in a file in the root of the stack def self.add_root(*args) roots << Pancake.get_root(*args) end add_root __FILE__, "defaults" def self.initialized? !!@initialized end def self.include_pancake_stack!(include_it = true) @include_pancake_stack = include_it end def self.include_pancake_stack? !!@include_pancake_stack end def initialize(app = nil, opts = {}) @app_name = opts.delete(:app_name) || self.class master = opts.delete(:master) self.class.initialize_stack(:master => master) unless self.class.initialized? self.class.set_as_master! if master Pancake.configuration.stacks[@app_name] = self # setup the configuration for this stack Pancake.configuration.configs[@app_name] = opts[:config] if opts[:config] self.configuration(@app_name) yield self.configuration(@app_name) if block_given? @app ||= self.class.new_endpoint_instance self.class.before_build_stack.each{|b| b.call(self, @app_name, opts)} mwares = self.class.middlewares @stack = Pancake::Middleware.build(@app, mwares) app_config = Pancake.configuration.configs(@app_name) app_config.stack = self.class app_config.router.configuration = app_config router = Pancake.configuration.configs[@app_name].router router.mount_applications! router.default(@stack) self.class.after_build_stack.each{ |blk| blk.call(self, @app_name, opts) } end # Construct a stack using the application, wrapped in the middlewares # @api public def self.stackup(opts = {}, &block) app = new(nil, opts, &block) r = Pancake.configuration.configs[app.app_name].router if include_pancake_stack? Pancake.start{r} else r end end # stackup def call(env) Pancake.configuration.configs[@app_name].router.call(env) end # get a new instance of the application for this stack # Ovewrite this to provide custom application initialization # :api: overwritable def self.new_endpoint_instance MISSING_APP end # Loads the rake task for this stack, and all mounted stacks # # To have your rake task loaded include a "tasks" director in the stack root # # Tasks found in all stack roots are loaded in the order of the stack roots declearations # # @api public def self.load_rake_tasks!(opts={}) stackup(opts) # load the application master = opts.delete(:master) # Don't get the other stacks to boot as master opts[:_rake_files_loaded] ||= [] # For each mounted application, load the rake tasks self::Router.mounted_applications.each do |app| if app.mounted_app.respond_to?(:load_rake_tasks!) app.mounted_app.load_rake_tasks!(opts) end end paths_for(:rake_tasks).each do |f| path = File.join(*f) unless opts[:_rake_files_loaded].include?(path) load path opts[:_rake_files_loaded] << path end end end # Symlinks files in the public roots of this stack and all mounted stacks. # Provided a mounted application responds to the +symlink_public_files!+ method then it will be called. # symlinks public files from all roots of the stacks to Pancake.root/public # # @api public # @author <NAME> def self.symlink_public_files! raise "Pancake root not set" unless Pancake.root public_root = File.join(Pancake.root, "public") mount_point = configuration.router.base_url unique_paths_for(:public).sort_by{|(r,p)| p}.each do |(r,p)| # don't try to symlink the symlinks origin_path = File.join(r, p) next if r == public_root || FileTest.directory?(origin_path) output_path = File.join(public_root, mount_point, p) unless File.exists?(File.dirname(output_path)) FileUtils.mkdir_p(File.dirname(output_path)) end # unless the dir exists... create it puts "Linking #{output_path}" FileUtils.ln_s(origin_path, output_path, :force => true) end router.mounted_applications.each do |s| if s.mounted_app.respond_to?(:symlink_public_files!) s.mounted_app.symlink_public_files! end end end # Specify a layout to use for this stack and all children stacks # Layouts are provided by Wrapt, and Pancake::Stacks::Short will use the layout when directed to by calling this method. Simply call it to activate layouts with the default options, or provide it with options to direct wrapt. # # You can specify a layout to use by name, provide it options or provide a block that you can use to set the layout via the environment. # # @params name [String] (optional) The name of the layout to use # @params opts [Hash] Options for use with Wrapt # # @block The block is used to determine at runtime which layout to use. It is yielded the environment where appropriate action can be taken. It assumes that you will set the layout object directly # # @example # # Direct the short stack to use a layout # layout # # # Set the layout to a non-default one # layout "non_standard" # # # Directly set the layout via the Wrapt::Layout object # layout do |env| # r = Rack::Request.new(env) # l = env['layout'] # if r.params['foo'] == 'bar' # l.template_name = "foo" # end # end # # @see Wrapt # @see Wrapt::Layout # @api public def self.apply_layout(name = nil, &blk) @use_layout = true @default_layout = name end def self.use_layout? if @use_layout @use_layout else @use_layout = superclass.respond_to?(:use_layout?) && superclass.use_layout? end end def self.default_layout if @default_layout @default_layout else @default_layout = superclass.respond_to?(:default_layout) && superclass.default_layout end end # Sets this as a master stack. This means that the "master" directory will be added to all existing stack roots def self.set_as_master! Pancake.master_stack ||= self # Want to add master to the roots for this stack only roots.dup.each do |root| unless root =~ /master\/?$/ roots << File.join(root, 'master') end end end def self.template(name,opts ={}) raise Errors::NotImplemented, "Stack may not be used for templates until it implements a template method" end def self.base_template_name raise Errors::NotImplemented, "Stack may not be used for templates until it implements a base_template_name method" end end # Stack end # Pancake require 'pancake/stack/configuration' require 'pancake/stack/router' require 'pancake/defaults/middlewares' require 'pancake/defaults/configuration'
hassox/pancake
lib/pancake/core_ext/class.rb
<gh_stars>1-10 class Class # Taken from extlib but uses a full Marshall.dump rather than just a dup. # This may not work for some data types. The data must be marshalable to use this method. # # Defines class-level inheritable attribute reader. Attributes are available to subclasses, # each subclass has a copy of parent's attribute. # # @param *syms<Array[#to_s]> Array of attributes to define inheritable reader for. # @return <Array[#to_s]> Array of attributes converted into inheritable_readers. # # @api public # # @todo Do we want to block instance_reader via :instance_reader => false # @todo It would be preferable that we do something with a Hash passed in # (error out or do the same as other methods above) instead of silently # moving on). In particular, this makes the return value of this function # less useful. def deep_copy_class_inheritable_reader(*ivars) instance_reader = ivars.pop[:reader] if ivars.last.is_a?(Hash) ivars.each do |ivar| self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.#{ivar} return @#{ivar} if self == #{self} || defined?(@#{ivar}) ivar = superclass.#{ivar} return nil if ivar.nil? && !#{self}.instance_variable_defined?("@#{ivar}") @#{ivar} = ivar && !ivar.is_a?(Module) && !ivar.is_a?(Numeric) ? Marshal.load(Marshal.dump(ivar)) : ivar end RUBY unless instance_reader == false self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{ivar} self.class.#{ivar} end RUBY end # unless end # ivars.each end # self.deep_inheritable_reader def deep_copy_class_inheritable_accessor(*ivars) deep_copy_class_inheritable_reader(*ivars) extlib_inheritable_writer(*ivars) end end # Class
hassox/pancake
lib/pancake/mixins/render/view_context.rb
require 'any_view' module Pancake module Mixins module Render class ViewContext # These are included as modules not for modularization, but because super can be called for the module versions include ::Tilt::CompileSite include ::AnyView::TiltBase class << self def capture_method_for(item) key = case item when Template item.renderer.class when Tilt::Template item end AnyView::TiltBase.capture_methods[key] end def concat_method_for(item) key = case item when Template item.renderer.class when Tilt::Template item end AnyView::TiltBase.concat_methods[key] end end attr_reader :_view_context_for def initialize(renderer_for = nil, opts = {}) opts.keys.each do |k,v| instance_variable_set("@#{k}", v) end @_inherit_helper = InheritanceHelper.new @_view_context_for = renderer_for end def inherits_from(ntos, name_or_opts = nil, opts = {}) name_or_template = case ntos when String, Symbol if ntos == :default! begin if @format Pancake.default_base_template(:format => @format) else Pancake.default_base_template end rescue :base end else ntos end when Pancake::Mixins::Render::Template ntos else if name_or_opts.kind_of?(Hash) opts = name_or_opts name_or_opts = nil end name_or_opts ||= ntos.base_template_name ntos.template(name_or_opts, opts) end @_inherit_helper.inherits_from = name_or_template end def content_block(label = nil, &block) return self if label.nil? current_label = @_inherit_helper.current_label @_inherit_helper.current_label = label capture_method = ViewContext.capture_method_for(_current_renderer) @_inherit_helper.blocks[label] << [block, capture_method] if @_inherit_helper.inherits_from.nil? result = _capture_content_block(label) send(ViewContext.concat_method_for(_current_renderer), result) end @_inherit_helper.current_label = current_label end def super @_inherit_helper.increment_super! result = _capture_content_block(@_inherit_helper.current_label) @_inherit_helper.decrement_super! result end def render(template, opts = {}, &blk) template = _view_context_for.template(template) raise TemplateNotFound unless template result = _with_renderer template do _current_renderer.render(self, opts, &blk) # only include the block once end if @_inherit_helper.inherits_from next_template = template.owner.template(@_inherit_helper.inherits_from) @_inherit_helper.inherits_from = nil result = _with_renderer next_template do render(next_template, opts) end end result end def partial(*args) _view_context_for.partial(*args) end def _with_renderer(renderer) orig_renderer = @_current_renderer @_current_renderer = renderer result = yield @_current_renderer = orig_renderer result end def _current_renderer @_current_renderer end private def _capture_content_block(label) blk, meth = @_inherit_helper.block_for(label) send(meth, &blk) end class InheritanceHelper attr_accessor :inherits_from, :current_label attr_reader :blocks, :super_index def initialize @blocks = Hash.new{|h,k| h[k] = []} @super_index = 0 end def block_for(label) @blocks[label][@super_index] end def increment_super! @super_index += 1 end def decrement_super! @super_index -= 1 end end end end end end
hassox/pancake
lib/pancake/paths.rb
module Pancake # Pancake::Paths provides a mixin for path management. # A path consists of a name, and paths + globs, and makes use of the Klass.roots that have been set as # file roots for each path and glob to be applied to. # Each name may have many (path + glob)s, so that many root paths may be added to the same name # # @example Adding Paths: # class Foo # extend Pancake::Paths # end # # Foo.push_paths(:model, "relative/path/to/models", "**/*.rb") # Foo.push_paths(:model, "another/path/to/models", "**/*.rb") # Foo.push_paths(:model, "yet/another") # # This will make available the directory and or full file paths for :model in the order they # were declared. # # When no glob is provided, the glob will be returned as nil # # @example Reading Paths: # Foo.dirs_for(:model) == ["#{root}/relative/path/to/models", "#{root}/another/path/to/models", "#{root}/yet/another"] # # Foo.dirs_and_glob_for(:model) == [ # ["#{root}/relative/path/to/models", "**/*.rb"], # ["#{root}/another/path/to/models", "**/*.rb"], # ["#{root}/yet/another", nil] # ] # # Foo.paths_for(:model) == [ # ["#{root}/relative/path/to/models", "/model1.rb"], # ["#{root}/path/to/models", "/model2.rb"], # ["#{root}/path/to/models/sub", "/model1.rb"], # ["#{root}/another/path/to/models", "/model3.rb"] # ] # # The paths are fully inheritable once they have extended a class. module Paths class NoPathsGiven < ArgumentError; end def self.extended(base) #:nodoc:# base.class_eval do deep_copy_class_inheritable_reader :_load_paths, :roots @_load_paths = ActiveSupport::OrderedHash.new @roots = [] end end # Push a named path and optional glob onto the list of paths associated with <name> # # @param [Symbol] name The name to associate with the given path and glob # @param [String, Array] paths A path or paths to associate with the namd and glob # @param [String, Nil] glob The glob to associate with the given path(s) and name # # @example No Glob: # MyClass.push_paths(:foo, "path/for/foo") # # @example Using a Glob: # MyClass.push_paths(:foo, "path/for/foo", "**/*.rb") # # @example Using Multiple paths: # MyClass.push_paths(:foo, ["path/one", "path/two"], "**/*.rb") # # @raise [Pancake::NoPathsGiven] raised when an empty paths array is provided # @author <NAME> # @since 0.1.1 # @api public def push_paths(name, paths, glob = nil) paths = [paths].flatten raise NoPathsGiven if paths.blank? _load_paths[name] ||= [] _load_paths[name] << [paths, glob] end # Provides the directories or raw paths that are associated with a given name. # # @param [Symbol] name The name for the paths group # @param [Hash] opts An options hash # @option opts [Boolean] :invert (false) inverts the order of the returned paths # # @example Read Directories: # MyClass.dirs_for(:models) # # @example Inverted Read: # MyClass.dirs_for(:models, :invert => true) # # @return [Array] An array of the paths # Returned in declared order unless the :invert option is set # @api public # @since 0.1.1 # @author <NAME> def dirs_for(name, opts = {}) if _load_paths[name].blank? [] else result = [] invert = !!opts[:invert] load_paths = invert ? _load_paths[name].reverse : _load_paths[name] roots.each do |root| load_paths.each do |paths, glob| paths = paths.reverse if invert result << paths.map{|p| File.join(root, p)} end end result.flatten end # if end # Provides the list of paths (directories) and the associated globs for a given name. # # @param [Symbol] name The name of the path group # @param [Hash] opts A hash of options # @option opts [Boolean] :invert (false) Inverts the order of the paths # # @example # MyClass.dirs_and_glob_for(:models) # # @return [Array] An array of [path, glob] arrays # Returned in declared order unless the :invert option is set # @api public # @since 0.1.1 # @author <NAME> def dirs_and_glob_for(name, opts = {}) if _load_paths[name].blank? [] else result = [] invert = !!opts[:invert] load_paths = invert ? _load_paths[name].reverse : _load_paths[name] roots.each do |root| load_paths.each do |paths, glob| paths = paths.reverse if invert paths.each do |path| result << [File.join(root, path), glob] end # paths.each end # load_paths.each end # roots.each result end # if end # Provides an expanded, globbed list of paths and files for a given name. # # @param [Symbol] name The name of the paths group # @param [Hash] opts An options hash # @option opts [Boolean] :invert (false) Inverts the order of the returned values # # @example # MyClass.paths_for(:model) # MyClass.paths_for(:model, :invert => true) # # @return [Array] # An array of [path, file] arrays. These may be joined to get the full path. # All matched files for [paths, glob] will be returned in declared and then found order unless +:invert+ is true. # Any path that has a +nil+ glob associated with it will be excluded. # # @api public # @since 0.1.1 # @author <NAME> def paths_for(name, opts = {}) result = [] dirs_and_glob_for(name, opts).each do |path, glob| next if glob.nil? paths = Dir[File.join(path, glob)] paths = paths.reverse if opts[:invert] paths.each do |full_path| result << [path, full_path.gsub(path, "")] end end result end # Provides an expanded, globbed list of paths and files for a given name. # The result includes only the last matched file of a given sub path and name. # # @param [Symbol] name The name of the paths group # @param [Hash] opts An options hash # @option opts [Boolean] :invert (false) Inverts the order of returned paths and files # # @example # #Given the following: # # /path/one/file1.rb # # /path/one/file2.rb # # /path/two/file1.rb # # MyClass.push_path(:files, ["/path/one", "/path/two"], "**/*.rb") # # MyClass.unique_paths_for(:files) # MyClass.unique_paths_for(:files, :invert => true) # # @return [Array] # Returns an array of [path, file] arrays # Results are retuned in declared order. Only unique files are returned (the file part - the path) # In the above example, the following would be returned for the standard call # [ # ["#{root}/path/one", "/file2.rb"], # ["#{root}/path/two", "/file1.rb"] # ] # For the inverted example the following is returned: # [ # ["#{root}/path/one/file2.rb"], # ["#{root}/path/one/file1.rb"] # ] # # @api public # @since 0.1.1 # @author <NAME> def unique_paths_for(name, opts = {}) tally = {} output = [] paths_for(name, opts).reverse.each do |ary| tally[ary[1]] ||= ary[0] output << ary if tally[ary[1]] == ary[0] end output.reverse end # unique_paths_for end end
hassox/pancake
lib/pancake/constants.rb
module Pancake module Constants ENV_LOGGER_KEY = "rack.logger" end end
hassox/pancake
spec/pancake/mixins/render/view_context_spec.rb
require 'spec_helper' describe Pancake::Mixins::Render::ViewContext do before do @masters = [Pancake.master_stack, Pancake.master_templates] $captures = [] class ::FooBar include Pancake::Mixins::Render attr_accessor :params, :data push_paths :views, "", "**/*" roots << File.join(File.expand_path(File.dirname(__FILE__)),"..","..", "fixtures", "render_templates", "view_context") end Pancake.master_stack = FooBar Pancake.master_templates = FooBar end after do Pancake.master_stack, Pancake.master_templates = @masters clear_constants :FooBar, :BarFoo end it "should setup the spec correctly" do %w(helper_methods.erb context.erb).each do |f| File.exists?(File.join(FooBar.roots.first, f)).should be_true end end describe "view contexts" do it "should inherit from Pancake::Mixins::Render::ViewContext" do FooBar::ViewContext.should inherit_from(Pancake::Mixins::Render::ViewContext) end end describe "inheriting classes" do before do FooBar::ViewContext.class_eval do def some_helper $captures << :some_helper end end class ::BarFoo < FooBar end end it "should inherit the view context when inheriting the outer class" do BarFoo::ViewContext.should inherit_from(FooBar::ViewContext) end end describe "delegation" do before do @renderer = mock("renderer", :null_object => true) end it "should provide access to the object the view context is rendering for" do context = FooBar::ViewContext.new(@renderer) context._view_context_for.should == @renderer end it "should grab the template from the view context when rendering" do context = FooBar::ViewContext.new(@renderer) @renderer.should_receive(:template).with(:foo).and_return(@renderer) context.render(:foo, :some => :opts) end end describe "capturing" do before do end it "should render the haml template with a capture" do result = FooBar.new.render(:capture_haml) result.should_not include("captured haml") context = $captures.first context.should_not be_nil context.instance_variable_get("@captured_haml").should include("captured haml") end it "should capture in erb" do result = FooBar.new.render(:capture_erb) result.should_not include("captured erb") context = $captures.first context.should_not be_nil context.instance_variable_get("@captured_erb").should include("captured erb") end it "should concat in haml" do result = FooBar.new.render(:concat_haml) result.should include("concatenated") end it "should concat in erb" do result = FooBar.new.render(:concat_erb) result.should include("concatenated") end end describe "content_block" do before do @foo = FooBar.new end it "should include the default text" do result = @foo.render(:inherited_haml_level_0) result.should include("inherited haml level 0") result.should include("default content block content") end it "should inherit the content block from a parent template" do result = @foo.render(:inherited_haml_level_1) result.should include("inherited haml level 0") result.should include("inherited haml level 1 content") end it "should inherit the default text in erb" do result = @foo.render(:inherited_erb_level_0) result.should include("inherited erb level 0") result.should include("default content block content") end it "should inherit the content block from a parent template in erb" do result = @foo.render(:inherited_erb_level_1) result.should include("inherited erb level 0") result.should include("inherited erb level 1 content") end it "should inherit erb from haml" do result = @foo.render(:inherited_erb_from_haml) result.should include("inherited haml level 0") result.should include("inherited erb content") end it "should inherit haml from erb" do result = @foo.render(:inherited_haml_from_erb) result.should include("inherited erb level 0") result.should include("inherited haml content") end it "should inherit a template multiple times" do result = @foo.render(:inherited_haml_level_2) result.should include("inherited haml level 0") result.should include("inherited haml level 1 content") result.should include("inherited haml level 2 content") end end describe "super blocks" do before do @foo = FooBar.new end it "should render the super text" do result = @foo.render(:super_haml_from_haml_0) result.should include("default content block content") end it "should render the super text and the new text" do result = @foo.render(:super_haml_from_haml_1) result.should include("default content block content") result.should include("new content with super") end it "should render the super text in erb templates" do result = @foo.render(:super_erb_from_erb_0) result.should include("default content block content") end it "should render the super text and the new text in erb" do result = @foo.render(:super_erb_from_erb_1) result.should include("new content with super") result.should include("default content block content") end it "should inherit haml from erb" do result = @foo.render(:super_haml_from_erb_0) result.should include("default content block content") end it "should inherit haml from erb with with additional contnet" do result = @foo.render(:super_haml_from_erb_1) result.should include("new content from haml") result.should include("default content block content") end it "should inherit erb from haml" do result = @foo.render(:super_erb_from_haml_0) result.should include("default content block content") end it "should inherit erb from haml" do result = @foo.render(:super_erb_from_haml_1) result.should include("new content from erb") result.should include("default content block content") end end describe "multiple context blocks" do before do @foo = FooBar.new end it "should allow nested default captures" do result = @foo.render(:nested_content_level_0) result.should include("level 0 content") result.should include("nested foo content") result.should include("nested bar content") end it "should allow inherited nested content to overwrite a given block" do result = @foo.render(:nested_content_level_1) result.should include("level 0 content") result.should include("nested foo content") result.should include("nested new bar content") end end describe "inheriting from a template object" do before do path = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "fixtures", "render_templates", "inherit")) class ::BarFoo include Pancake::Mixins::Render push_paths :views, "", "**/*" def self._template_name_for(name, opts = {}) opts[:format] ||= :html r = "#{name}.#{opts[:format]}" end end class ::FooBar def self._template_name_for(name, opts = {}) opts[:format] ||= :html r = "#{name}.#{opts[:format]}" end end FooBar.roots << File.join(path, "foo") BarFoo.roots << File.join(path, "bar") @app = FooBar.new @bar = BarFoo.new Pancake.master_templates = BarFoo end it "should inherit from it's own stack with a name" do result = @app.render(:simple) result.should include("Foo Base") result.should include("Simple Foo Content") end it "should inherit from a stack, name pair" do result = @app.render(:explicit) result.should include("Bar Layout") result.should include("Explicit Content") end it "should inherit from the pancake default using :defaults!" do result = @app.render(:defaults) result.should include("Bar Base") result.should include("Defaults Content") end it "should use it's own base template when pancake does not have one set" do Pancake.master_templates = nil result = @app.render(:defaults) result.should include("Foo Base") result.should include("Defaults Content") end it "should inherit multiple levels to an explicit base template" do result = @app.render(:from_explicit) result.should include("Bar Layout") result.should include("Explicit Content") result.should include("From Explicit Content") end it "should inherit to an explicit layout that inherits to a scoped template" do result = @app.render(:from_implicit_scope) result.should include("Bar Base") result.should include("Bar Implicit Scope Content") result.should include("From Implicit Scope Content") end end describe "partials" do before do @foo = FooBar.new @collection = %w(one two three four) $captures = [] end it "should use the _partial_template_name_for method to find a partial" do @foo.should_receive(:_partial_template_name_for).with(:basic, {}).and_return("_basic") result = @foo.partial(:basic) end it "should render a partial with the partial call" do result = @foo.partial(:basic) result.should include("In Partial Basic") end it "should render from within a template" do result = @foo.render(:contains_partial) result.should include("In Partial Basic") end it "should use a different view context instance for the partial" do result = @foo.render(:contains_partial) $captures.should have(2).items $captures.first.should_not == $captures.last end it "should allow me to specify locals for use in the partial" do result = @foo.partial(:with_locals, :foo => "this is foo", :bar => "and this is bar") result.should include("foo == this is foo") result.should include("bar == and this is bar") end it "should render a partial with an object as the local name" do result = @foo.partial(:local_as_name, :with => "value of local as name") result.should include("local_as_name == value of local as name") end it "should render a partial with many objects with the obj as a local with the partial name" do result = @foo.partial(:local_as_name, :with => @collection) @collection.each do |val| result.should include("local_as_name == #{val}") end end it "should render a partial with an object with a specified name" do result = @foo.partial(:foo_as_name, :with => "jimmy", :as => :foo) result.should include("foo == jimmy") end it "should render a partial with many objects as a local with a specified name" do result = @foo.partial(:foo_as_name, :with => @collection, :as => :foo) @collection.each do |val| result.should include("foo == #{val}") end end end end
hassox/pancake
lib/pancake/defaults/configuration.rb
class Pancake::PancakeConfig < Pancake::Configuration::Base default :log_path, Proc.new{ "log/pancake_#{Pancake.env}.log"} default :log_level, :info default :log_delimiter, " ~ " default :log_auto_flush, true default :log_to_file, Proc.new{ Pancake.env == "production" } default :log_stream, Proc.new{ _log_stream } def _log_stream if Pancake.configuration.log_to_file log_dir = File.expand_path(File.join(Pancake.root, File.dirname(log_path))) FileUtils.mkdir_p(log_dir) log = File.join(log_dir, File.basename(log_path)) File.open(log, (File::WRONLY | File::APPEND | File::CREAT)) else STDOUT end end def reset_log_stream! values.delete(:log_stream) end def stacks(label = nil) @stacks ||= {} result = label.nil? ? @stacks : @stacks[label] yield result if block_given? result end def configs(label = nil) @configs ||= Hash.new do |h,k| if (k.is_a?(Class) || k.is_a?(Module)) && defined?(k::Configuration) h[k] = k::Configuration.new else nil end end result = label.nil? ? @configs : @configs[label] yield result if block_given? result end end
hassox/pancake
lib/pancake/stack/router.rb
module Pancake class Stack inheritable_inner_classes :Router class Router < Pancake::Router; end def self.router @router ||= begin if superclass.respond_to?(:router) && superclass.router r = superclass.router.clone(self::Router) r.stack = self else r = self::Router.new r.stack = self end yield r if block_given? r end end end end
hassox/pancake
lib/pancake/mixins/render/template.rb
module Pancake module Mixins module Render class Template class UnamedTemplate < Pancake::Errors::NotFound; end class NotFound < Pancake::Errors::NotFound; end attr_reader :name, :path, :renderer, :owner def initialize(name, owner, path) @name, @owner, @path = name, owner, path raise UnamedTemplate unless name raise NotFound unless File.exists?(path) @renderer = Tilt.new(path) end def render(context = ViewContext.new, opts = {}) @renderer.render(context, opts) end end #Template end #Render end #Mixins end #Pancake
hassox/pancake
spec/pancake/mixins/render/template_spec.rb
require 'spec_helper' describe Pancake::Mixins::Render::Template do before do $captures = [] @templates_path = File.join(File.expand_path(File.dirname(__FILE__)), "..", "..", "fixtures", "render_templates", "templates") class ::FooBar include Pancake::Mixins::Render end end after do clear_constants :FooBar, :BarFoo end describe "Creation" do it "should create a template with a name and a path" do result = FooBar::Template.new(:context, FooBar, File.join(@templates_path, "context.erb")) result.should_not be_nil end it "should raise an error when creating a template without a name" do lambda do FooBar::Template.new(nil, FooBar, File.join(@templates_path, "context.erb")) end.should raise_error(Pancake::Mixins::Render::Template::UnamedTemplate) end it "should raise an error when createing a template withouth a valid file name" do lambda do FooBar::Template.new(:foo, FooBar, "/not/a/real/file.erb") end.should raise_error(Pancake::Mixins::Render::Template::NotFound) end it "should raise an error when it cannot create a rendering object for the file" do lambda do FooBar::Template.new(:foo, FooBar, "/not/registed") end.should raise_error end describe "accessing information" do before do @template = FooBar::Template.new(:context, FooBar, File.join(@templates_path, "context.erb")) end it "should provide access to it's name" do @template.name.should == :context end it "should provide access to it's path" do @template.path.should == File.join(@templates_path, "context.erb") end it "should render the template" do @template.render.should match(/in context/m) end describe "contexts" do before do @context = mock("context") end it "should render with the given context" do @template.render(@context) $captures.first.should == @context end end end end end
hassox/pancake
spec/spec_helper.rb
<reponame>hassox/pancake $TESTING=true require 'rubygems' require 'date' require 'rack' require 'rack/test' require 'spec/rake/spectask' require 'spec' require 'haml' require 'json' ENV['RACK_ENV'] = "test" $:.unshift File.dirname(__FILE__) $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'pancake' Dir[File.join(File.dirname(__FILE__), "helpers", "**/*.rb")].each{|f| require f} Spec::Runner.configure do |config| config.include(Pancake::Test::Matchers) config.include(Pancake::Test::Helpers) config.include(Rack::Test::Methods) end
hassox/pancake
spec/pancake/middleware_spec.rb
<reponame>hassox/pancake require 'spec_helper' describe "Pancake::Middleware" do before(:all) do $pk_mid = Pancake.middlewares.dup end after(:all) do Pancake.middlewares.replace $pk_mid end before(:each) do Pancake.middlewares.clear def app @app end def default_env Rack::MockRequest.env_for end $current_env = {} class ::GeneralMiddleware attr_accessor :app def initialize(app, opts={});@app = app; end def mark_env(env) env["p.s.c"] ||= [] env["p.s.c"] << self.class end def call(env) mark_env(env) @app.call(env) end end # GeneralMiddlware class ::FooApp < Pancake::Stack def self.new_endpoint_instance; self end def self.call(env) $current_env = env [200,{"Content-Type" => "text/plain"}, [name]] end end # FooApp FooApp.roots << Pancake.get_root("/tmp") end after(:each) do clear_constants(:MasterApp, :FooApp, :BarApp, :BazApp, :GeneralMiddleware, :BarMiddle, :FooMiddle, :BazMiddle, :PazMiddle) end describe "pancake middlewares" do before(:each) do @root = File.join(Pancake.get_root(__FILE__), "fixtures", "foo_stack") @the_app = Proc.new{|e| } Pancake::StackMiddleware.reset! end it "should allow me to add middleware to pancake" do Pancake.use GeneralMiddleware @app = Pancake.start(:root => @root){ FooApp.stackup } Pancake.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware] get "/" $current_env["p.s.c"].should include(GeneralMiddleware) end it "should allow me to add multiple middlewares to panckae" do class ::FooMiddle < GeneralMiddleware; end Pancake.use GeneralMiddleware FooApp.use FooMiddle @app = Pancake.start(:root => @root){ FooApp.stackup } get "/" $current_env["p.s.c"].should == [GeneralMiddleware, FooMiddle] end it "should put the pancake middlewares out in front" do class ::FooMiddle < GeneralMiddleware; end class ::BarMiddle < GeneralMiddleware; end class ::BarApp < FooApp; end class ::BazApp < FooApp; end class ::MasterApp < FooApp; end BarApp.use BarMiddle BazApp.use FooMiddle Pancake.use GeneralMiddleware MasterApp.router do |r| r.mount(BarApp, "/bar") r.mount(BazApp, "/baz") end @app = Pancake.start(:root => @root){ MasterApp.stackup } result = get "/baz" $current_env["p.s.c"].should == [GeneralMiddleware, FooMiddle] reult = get "/bar" $current_env["p.s.c"].should == [GeneralMiddleware, BarMiddle] end end it "should allow me to add middleware" do FooApp.class_eval do use GeneralMiddleware end @app = FooApp.stackup get "/" $current_env["p.s.c"].should include(GeneralMiddleware) end it "should allow me to add multiple middlewares" do class ::FooMiddle < GeneralMiddleware; end FooApp.class_eval do use GeneralMiddleware use FooMiddle end @app = FooApp.stackup get "/" [GeneralMiddleware, FooMiddle].each do |m| $current_env["p.s.c"].should include(m) end end it "should allow you to add middleware from outside the class" do FooApp.use GeneralMiddleware @app = FooApp.stackup get "/" $current_env["p.s.c"].should == [GeneralMiddleware] end describe "replace middleware" do before(:each) do FooApp.stack(:replaceable).use(GeneralMiddleware, :some => :option){ :original } class FooMiddle < GeneralMiddleware; end end it "should replace the middleware with another middleware" do orig = FooApp::StackMiddleware[:replaceable] orig.middleware.should == GeneralMiddleware orig.args.should == [{:some => :option}] FooApp.stack(:replaceable).use(FooMiddle, :foo => :options) replaced = FooApp.stack(:replaceable) replaced.middleware.should == FooMiddle replaced.args.should == [{:foo => :options}] end end describe "deleteing middleware" do before(:each) do FooApp.stack(:deleteable).use(GeneralMiddleware, :some => :option){ :original } end it "should delete the middleware" do orig = FooApp::StackMiddleware[:deleteable] orig.should_not be_nil orig.middleware.should == GeneralMiddleware FooApp.stack(:deleteable).delete! FooApp::StackMiddleware[:deleteable].should be_nil end it "should not include middleware that depends on being deleted" do class FooMiddle < GeneralMiddleware; end FooApp.stack(:foo, :after => :deleteable).use(FooMiddle) FooApp.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware, FooMiddle] FooApp.stack(:deleteable).delete! FooApp.middlewares.map{|m| m.middleware}.should == [] end end describe "edit middleware" do before(:each) do FooApp.stack(:editable).use(GeneralMiddleware,:some => :config) end it "should allow me to update settings for middleware" do FooApp.stack(:editable).args.should == [{:some => :config}] FooApp.stack(:editable).args = [{:foo => :bar}] FooApp.stack(:editable).args.should == [{:foo => :bar}] end end describe "Inherited middleware" do before(:each) do class FooMiddle < GeneralMiddleware; end class BarMiddle < GeneralMiddleware; end end it "should inherit middleware from it's parent class" do FooApp.use GeneralMiddleware FooApp.use FooMiddle class BarApp < FooApp; end BarApp.middlewares.should == FooApp.middlewares end it "should not pollute the parent when including new middlewares in the child" do FooApp.use GeneralMiddleware class BarApp < FooApp; end BarApp.use FooMiddle BarApp.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware, FooMiddle] FooApp.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware] end describe "editing inherited middlware" do it "should not edit the parent when editing the child" do FooApp.use GeneralMiddleware, :some => :option class BarApp < FooApp; end BarApp.stack(GeneralMiddleware).middleware.should == GeneralMiddleware BarApp.stack(GeneralMiddleware).args = [{:foo => :bar}] BarApp.stack(GeneralMiddleware).args.should == [{:foo => :bar}] FooApp.stack(GeneralMiddleware).args.should == [{:some => :option}] end it "should not update the parent when updating a childs config" do FooApp.use GeneralMiddleware, :some => :option class BarApp < FooApp; end BarApp.stack(GeneralMiddleware).args[0][:another] = :option FooApp.stack(GeneralMiddleware).args.should == [{:some => :option}] BarApp.stack(GeneralMiddleware).args.should == [{:some => :option, :another => :option}] end end end describe "Stacks should inherit middleware" do before(:all) do $pk_middlewares = Pancake::Stack.middlewares.dup end after(:all) do Pancake::Stack.middlewares.replace $pk_middlewares end before(:each) do class FooMiddle < GeneralMiddleware; end class BarMiddle < GeneralMiddleware; end end after(:each) do Pancake::Stack::StackMiddleware.reset! end it "should clear the middlewares for the specs" do Pancake::Stack.middlewares.should be_blank end it "should allow me to set middlewares on Pancake::Stack" do Pancake::Stack.use GeneralMiddleware Pancake::Stack.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware] end it "should carry down middlewares from the Pancake::Stack to inherited stacks" do Pancake::Stack.use GeneralMiddleware class FooApp < Pancake::Stack; end FooApp.use FooMiddle Pancake::Stack.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware] FooApp.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware, FooMiddle] end it "should let me have different middlewares in different children" do Pancake::Stack.use GeneralMiddleware class FooApp < Pancake::Stack; end FooApp.use FooMiddle class BarApp < Pancake::Stack; end BarApp.use BarMiddle FooApp.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware, FooMiddle] BarApp.middlewares.map{|m| m.middleware}.should == [GeneralMiddleware, BarMiddle] end describe "Stack Middleware Enabled Constant", :shared => true do before(:each) do raise "You must set a @konstant for the stack construction spec" unless @konstant @konstant::StackMiddleware.reset! end describe "named middleware" do it "should allow me to name a #{@konstant} middleware" do @konstant.stack(:foo).use(GeneralMiddleware) @konstant.stack[:foo].middleware.should == GeneralMiddleware end it "should implicitly name a middleware" do @konstant.stack.use(GeneralMiddleware) @konstant.stack[GeneralMiddleware].middleware.should == GeneralMiddleware end end describe "before/after middleware" do before(:each) do class ::BazMiddle < GeneralMiddleware; end class ::PazMiddle < GeneralMiddleware; end end # :FooApp, :BarApp, :BazApp, :GeneralMiddleware, :BarMiddle, :FooMiddle, :BazMiddle, :PazMiddle it "should allow me to add middleware before other middleware" do @konstant.use(GeneralMiddleware) @konstant.stack(:bar).use(BarMiddle) @konstant.stack(:foo, :before => :bar).use(FooMiddle) result = @konstant.middlewares.map{|m| m.middleware} result.should == [GeneralMiddleware, FooMiddle, BarMiddle] end it "should allow me to add middleware after other middleware " do @konstant.use(BarMiddle) @konstant.stack(:general).use(GeneralMiddleware) @konstant.stack(:foo, :after => BarMiddle).use(FooMiddle) result = @konstant.middlewares.map{|m| m.middleware} result.should == [ BarMiddle, FooMiddle, GeneralMiddleware] end it "should allow me to add middleware arbitrarily and have it in the correct order" do @konstant.use(GeneralMiddleware) @konstant.stack(:bar).use(BarMiddle) @konstant.stack(:foo, :before => :bar).use(FooMiddle) @konstant.stack(:baz, :after => :foo).use(BazMiddle) @konstant.stack(:paz, :before => GeneralMiddleware).use(PazMiddle) result = @konstant.middlewares.map{|m| m.middleware} result.should == [PazMiddle, GeneralMiddleware, FooMiddle, BazMiddle, BarMiddle] end end end describe "Pancake Middleware Construction" do before(:each) do @konstant = Pancake end it_should_behave_like("Stack Middleware Enabled Constant") end describe "Pancake Stack Middleware" do before(:each) do @konstant = Pancake::Stack end it_should_behave_like("Stack Middleware Enabled Constant") end describe "An inherited panckae stack app" do before(:each) do class ::FooApp < Pancake::Stack; end @konstant = FooApp end it_should_behave_like("Stack Middleware Enabled Constant") end describe "a deeply inherited stack app" do before(:each) do class ::FooApp < Pancake::Stack; end class ::BarApp < FooApp; end @konstant = BarApp end it_should_behave_like("Stack Middleware Enabled Constant") end it "should allow me to inherit middleware from a parent stack" do class ::FooApp < Pancake::Stack; end FooApp.use(GeneralMiddleware) class ::BarApp < FooApp; end BarApp.stack(:foo).use(FooMiddle) BarApp.stack(:bar, :after => GeneralMiddleware).use(BarMiddle) result = BarApp.middlewares.map{|m|m.middleware} result.should == [GeneralMiddleware, BarMiddle, FooMiddle] end end # Stack Inheritance describe "types of stacks" do before(:each) do class FooMiddle < GeneralMiddleware; end class BarMiddle < GeneralMiddleware; end class BazMiddle < GeneralMiddleware; end FooApp.stack(:general ).use(GeneralMiddleware) FooApp.stack(:foo ).use(FooMiddle) FooApp.stack(:bar ).use(BarMiddle) FooApp.stack(:baz ).use(BazMiddle) end end end
hassox/pancake
spec/pancake/fixtures/tasks/root2/tasks/task1.rake
$captures << "root2/tasks/task1.rake"
hassox/pancake
lib/pancake/middlewares/static.rb
module Pancake module Middlewares class Static attr_accessor :app, :stack def initialize(app, stack) @app, @stack = app, stack unless Pancake::Paths === stack raise "#{self.class} needs to be initialized with a stack (or something including Pancake::Paths)" end end def call(env) static_file = nil root = stack.dirs_for(:public).detect do |root| root = File.expand_path(root) file_name = Rack::Utils.unescape(File.expand_path(File.join(root, env['PATH_INFO'].chomp("/")))) # If the client is asking for files outside the public directory, return missing # i.e. get "/../../foo.secret" if file_name !~ /^#{root}/ return Rack::Response.new("Not Found", 404).finish end # If we get to here and the file exists serve it if File.file?(file_name) static_file = file_name end end if static_file Rack::Response.new(File.open(static_file), 200, { 'Content-Type' => Rack::Mime.mime_type(File.extname(static_file)) }).finish else app.call(env) end end end end end
hassox/pancake
spec/pancake/stack/stack_spec.rb
require 'spec_helper' describe "Pancake::Stack" do before(:each) do class ::StackSpecStack < Pancake::Stack; end class ::OtherSpecStack < Pancake::Stack; end StackSpecStack.roots.clear end after(:each) do clear_constants(:StackSpecStack, :FooSpecStack, :OtherSpecStack) end describe "roots" do it "should provide access to setting the roots" do StackSpecStack.roots.should be_empty StackSpecStack.roots << File.expand_path(File.dirname(__FILE__)) StackSpecStack.roots.should include(File.expand_path(File.dirname(__FILE__))) end it "should provide access to adding a root" do StackSpecStack.roots.should be_empty StackSpecStack.roots << Pancake.get_root(__FILE__) StackSpecStack.roots.should include(File.expand_path(File.dirname(__FILE__))) end it "should allow me to get multiple roots in the order they're added" do StackSpecStack.roots.should be_empty StackSpecStack.roots << Pancake.get_root(__FILE__) StackSpecStack.roots << "/tmp" StackSpecStack.roots.should == [Pancake.get_root(__FILE__), "/tmp"] end it "should iterate over the roots in the direction they're added" do StackSpecStack.roots.should be_empty StackSpecStack.roots << Pancake.get_root(__FILE__) StackSpecStack.roots << "/foo" StackSpecStack.roots.map{|f| f}.should == [Pancake.get_root(__FILE__), "/foo"] end it "should allow me to set a root with a file" do StackSpecStack.add_root(__FILE__) StackSpecStack.roots.should include(Pancake.get_root(__FILE__)) end end # roots # describe "initialize stack" do it "should mark a stack as initialized once it has called the initialize_stack method" do StackSpecStack.roots << ::Pancake.get_root(__FILE__) StackSpecStack.initialize_stack StackSpecStack.should be_initialized end it "should not be initialized when it has not called initialize_stack" do StackSpecStack.should_not be_initialized end describe "include pancake stack" do before do $captures = [] clear_constants(:GeneralMiddleware, :MySpecStack) Pancake::StackMiddleware.reset! class ::GeneralMiddleware def initialize(app) @app = app end def call(env) $captures << self.class @app.call(env) end end Pancake.stack(:general).use(GeneralMiddleware) end it "should let me tell the stack to include the pancake stack" do lambda do StackSpecStack.include_pancake_stack! end.should_not raise_error end it "should remember that I told it to include the pancake stack" do StackSpecStack.include_pancake_stack! StackSpecStack.include_pancake_stack?.should be_true end it "should not remember when inherited" do StackSpecStack.include_pancake_stack! class ::MySpecStack < StackSpecStack; end MySpecStack.include_pancake_stack?.should be_false end it "should build the stack with the pancake stack out front" do StackSpecStack.roots << Pancake.get_root(__FILE__) StackSpecStack.include_pancake_stack! stack = StackSpecStack.stackup stack.should be_an_instance_of(GeneralMiddleware) end end describe "master stack" do before do @b4 = Pancake.master_stack end after do Pancake.master_stack = @b4 end it "should set the stack to be master, and include the master dir in each root" do StackSpecStack.add_root(__FILE__) before_roots = StackSpecStack.roots.dup s = StackSpecStack.stackup(:master => true) before_roots.each do |r| StackSpecStack.roots.should include(File.join(r, "master")) end Pancake.master_stack.should == StackSpecStack end it "should not set a master stack when one has already been set" do StackSpecStack.add_root(__FILE__) OtherSpecStack.add_root(__FILE__) StackSpecStack.stackup(:master => true) Pancake.master_stack.should == StackSpecStack OtherSpecStack.stackup(:master => true) Pancake.master_stack.should == StackSpecStack end end describe "loading rake tasks" do before do $captures = [] StackSpecStack.add_root(__FILE__, "..", "fixtures", "tasks", "root1") end it "should load the rake tasks in the stacks root" do StackSpecStack.load_rake_tasks! $captures.should == ["root1/tasks/task1.rake", "root1/tasks/task2.rake"] end it "should load the rake tasks in order of the roots" do StackSpecStack.add_root(__FILE__, "..", "fixtures", "tasks", "root2") StackSpecStack.load_rake_tasks! $captures.should == [ "root1/tasks/task1.rake", "root1/tasks/task2.rake", "root2/tasks/task1.rake", "root2/tasks/task2.rake" ] end it "should load rake tasks for mounted applications" do class ::FooSpecStack < Pancake::Stack add_root(__FILE__, "..", "fixtures", "tasks", "root2") end StackSpecStack.router.mount(FooSpecStack, "/foo") StackSpecStack.load_rake_tasks! # Mounted stacks should have their rake tasks loaded first so they can be overwritten $captures.should == [ "root2/tasks/task1.rake", "root2/tasks/task2.rake", "root1/tasks/task1.rake", "root1/tasks/task2.rake" ] end it "should not try to load rake tasks of a mounted app that does not respond to load_rake_tasks!" do class ::FooSpecStack < Object def self.call(env); Rack::Response.new("OK").finish; end end StackSpecStack.router.mount(FooSpecStack, "/foo/spec") lambda do StackSpecStack.load_rake_tasks! end.should_not raise_error end end end
hassox/pancake
spec/pancake/defaults/configuration_spec.rb
<gh_stars>1-10 require 'spec_helper' describe "Pancake configuration defaults" do describe "logging defaults" do before do Pancake.root = Pancake.get_root(__FILE__) end after do Pancake.reset_configuration FileUtils.rm_rf(File.join(Pancake.root, "log")) end it "should set the log path" do path = Pancake.configuration.log_path path.should == "log/pancake_#{Pancake.env}.log" end it "should set the log level to :info" do Pancake.configuration.log_level.should == :info end it "should set the delimiter to ~ " do Pancake.configuration.log_delimiter.should == " ~ " end it "should set auto flush to true" do Pancake.configuration.log_auto_flush.should be_true end it "should set log to file to false" do Pancake.configuration.log_to_file.should be_false end it "should set log to file to true if env is production" do Pancake.stub(:env).and_return("production") Pancake.configuration.log_to_file.should be_true end it "should set the log_stream to STDOUT by default" do Pancake.configuration.log_stream.should === STDOUT end it "should set the log stream to a file path when told to log to file" do Pancake.configuration.log_to_file = true result = Pancake.configuration.log_path result.should match(/\log\/pancake_#{Pancake.env}\.log$/) end it "should create the directory if it doesn't exist" do File.exists?(File.join(Pancake.root, "log")).should be_false Pancake.configuration.log_to_file = true Pancake.configuration.log_stream File.exists?(File.join(Pancake.root, "log")).should be_true end end end
hassox/pancake
lib/pancake/mixins/request_helper.rb
module Pancake module Mixins # Some helpers for requests that come in handy for applications that # are part of stacks module RequestHelper VARS_KEY = 'request.variables' # A data area that allows you to carry data accross middlewares, controller / views etc. # Stores the data in session for the length of the request. # # @example # vars[:user] = @user # v[:user] == vault[:user] # # This is now stored in the environment and is available later def vars env[VARS_KEY] ||= Hashie::Mash.new env[VARS_KEY] end alias_method :v, :vars # Get the configuration for this request. This will be updated as the request makes its way through the stacks def configuration request.env[Pancake::Router::CONFIGURATION_KEY] end # Generate a url for the current stacks router. # # @example # class MyApp # router do |r| # r.add("/foo").name(:foo) # end # # include Pancake::RequestHelper # # snip # def call(env) # @env = env # url(:foo) # => "/foo" # end # end # # @see Usher # @see Pancake::Router # @api public # @author <NAME> def url(name, opts = {}) configuration.router.url(name, opts) end # Generate the base url for the router that got you to this point. # # @example # class MyApp # router do |r| # r.mount(SomeApp, "/some_app/:version") # end # # include Pancake::RequestHelper # def call(env) # @env = env # base_url(:version => "1.0" #=> "/some_app/1.0 # end # end # # @see Usher # @see Pancake::Router.base_url_for # @see Pancake::Router#base_url # @api public # @author <NAME> def base_url(opts={}) configuration.router.base_url(opts) end # Generate a url for any registered configuration with a router # # @example # # an application declared with MyApp.stackup(:app_name => #:some_app) # url_for(:some_app, :my_named_route) # # # An application with no name specified # url_for(MyApp, :my_named_route) # # @see Usher # @see Pancake::Router # @api public # @author <NAME> def url_for(app_name, name_or_opts, opts = {}) if konfig = Pancake.configuration.configs[app_name] konfig.router.generate(name_or_opts, opts) else raise Pancake::Errors::UnknownConfiguration end end # A setter for the rack environment # @api public def env=(env) @env = env end # An accessor for the rack environment variable # @api public def env @env ||= {} end # A handy request method that gets hold of the current request # object for the current rack request. # Any including class _must_ provide an +env+ method that exposes # the rack request environment # # @see Rack::Request # @api public # @author <NAME> def request @request ||= Rack::Request.new(env) end # Provides access to the logger object in rack.logger # # # @api public # @author <NAME> def logger env[Pancake::Constants::ENV_LOGGER_KEY] end def negotiate_content_type!(*allowed_types) return content_type if content_type allowed_types = allowed_types.flatten opts = allowed_types.pop if allowed_types.last.kind_of?(Hash) opts ||= {} if opts[:format] cont, ct, mt = Pancake::MimeTypes.negotiate_by_extension(opts[:format].to_s, allowed_types) else env["HTTP_ACCEPT"] ||= "*/*" cont, ct, mt = Pancake::MimeTypes.negotiate_accept_type(env["HTTP_ACCEPT"], allowed_types) end raise Errors::NotAcceptable unless cont headers["Content-Type"] = ct self.mime_type = mt self.content_type = cont cont end def content_type env['pancake.request.format'] end def content_type=(format) env['pancake.request.format'] = format end def mime_type env['pancake.request.mime'] end def mime_type=(mime) env['pancake.request.mime'] = mime end end # RequestHelper end # Mixins end # Pancake
hassox/pancake
lib/pancake/router.rb
module Pancake # Generate a url for any pancake configuration that has a router # # @example # Pancake.url(UserManamgent, :login) # => "/users/login" # @api public def self.url(app_name, name_or_opts, opts = {}) config = Pancake.configuration.configs(app_name) the_router = if config && config.router config.router elsif app_name.respond_to?(:router) app_name.router else raise Pancake::Errors::UnknownRouter end the_router.url(name_or_opts, opts) end def self.base_url_for(app_name, opts={}) config = Pancake.configuration.configs(app_name) the_router = if config && config.router config.router elsif app_name.respond_to?(:router) raise Pancake::Errors::UnknownRouter end the_router.respond_to?(:base_url) ? the_router.base_url(opts) : "/" end # The pancake router uses a http_router router # @see http://github.com/joshbuddy/http_router # @since 0.1.2 # @author <NAME> class Router < HttpRouter attr_accessor :stack CONFIGURATION_KEY = "pancake.request.configuration".freeze ROUTE_KEY = "pancake.request.matching_route".freeze LAYOUT_KEY = "pancake.apply_layout".freeze class RackApplicationExpected < ArgumentError; end attr_accessor :configuration extlib_inheritable_accessor :mounted_applications self.mounted_applications = [] class MountedApplication attr_accessor :mounted_app, :mount_path, :args, :stackup_with, :options,:mounted def initialize(mounted_app, mount_path, opts = {}) @mounted_app, @mount_path = mounted_app, mount_path @stackup_with = opts.delete(:_stackup) || :stackup @args = opts.delete(:_args) || [] @options = opts end def name(name = nil) unless name.nil? @name = name end @name end def mounted? !!@mounted end def mount!(route) app = nil if mounted_app.respond_to?(stackup_with) app = mounted_app.send(stackup_with, *args) else app = mounted_app end route.to(app) route.name(@name) if @name route.partial route end end def dup puts "Called DUP: #{caller.first}" clone end # Mounts an application in the router as a sub application in the # url space. This will route directly to the sub application and # skip any middlewares etc defined on a stack def mount(mounted_app, path, options = {}) mounted_app = MountedApplication.new(mounted_app, path, options) self.class.mounted_applications << mounted_app mounted_app end def mount_applications! # need to set them as mounted here before we actually to mount them. # if we just mounted them, the inheritance of the routes would mean that only the first would be mounted on this class # and the rest would be mounted on the child class apps = self.class.mounted_applications.select do |a| a.mounted? ? false : (a.mounted = true) end apps.each do |app| route = add(app.mount_path, app.options) app.mount!(route) end end def base_url(opts = {}) url_mount.nil? ? "/" : url_mount.url(opts) end def call(env) apply_layout = env[LAYOUT_KEY] env[LAYOUT_KEY] = true if stack && stack.use_layout? orig_config = env[CONFIGURATION_KEY] orig_route = env[ROUTE_KEY] env[CONFIGURATION_KEY] = configuration super(env) ensure env[CONFIGURATION_KEY] = orig_config env[ROUTE_KEY] = orig_route env[LAYOUT_KEY] = apply_layout end private def process_params(env, response) request = Rack::Request.new(env) request.env['rack.request.query_hash'] = request.params.dup super env['router.params'] = Hashie::Mash.new(env['router.params']) if env['router.params'] && ! env['router.params'].empty? request.env['rack.request.query_hash'].merge!(env['router.params']) unless env['router.params'].nil? # make the request params a hashie mash request.env['rack.request.query_hash'] = Hashie::Mash.new(request.params) unless request.params.kind_of?(Hashie::Mash) end end end
hassox/pancake
spec/pancake/mixins/stack_helper_spec.rb
<filename>spec/pancake/mixins/stack_helper_spec.rb<gh_stars>1-10 require 'spec_helper' describe Pancake::Mixins::StackHelper do before do class ::FooStack < Pancake::Stack class Bar include Pancake::Mixins::StackHelper end end end after do clear_constants :FooStack, :BarStack, :FooBar end it "should provide access to the stack helper to the Bar class" do FooStack::Bar.stack_class.should == FooStack end it "should track the class for a newly namespaced stack" do class ::BarStack < FooStack class Bar < ::FooStack::Bar end end BarStack::Bar.stack_class.should == BarStack end it "should raise an exception when including it into a class that is not of a stack" do lambda do class ::FooBar include Pancake::Mixins::StackHelper end end.should raise_error end it "should remember the stack it was initially mixed into if it's inherited to a non namespaced class" do class ::FooBar < FooStack::Bar; end FooBar.stack_class.should == FooStack end it "should provide access to the stack helper from an instance of the Bar class" do FooStack::Bar.new.stack_class.should == FooStack end end
hassox/pancake
spec/pancake/configuration_spec.rb
<reponame>hassox/pancake<filename>spec/pancake/configuration_spec.rb require 'spec_helper' describe "Pancake::Configuration" do it "should let me make a new configuration" do conf_klass = Pancake::Configuration.make conf_klass.should inherit_from(Pancake::Configuration::Base) end describe "usage" do before(:each) do @Conf = Pancake::Configuration.make end it "should let me set defaults" do @Conf.default :foo, :bar c = @Conf.new c.foo.should == :bar @Conf.new.foo.should == :bar end it "should let me set a description on the default" do @Conf.default :foo, :bar @Conf.default :bar, :baz, "A description of bar" c = @Conf.new c.foo.should == :bar c.bar.should == :baz c.defaults[:foo][:description].should == "" c.defaults[:bar][:description].should == "A description of bar" end it "should allow me to make multiple different configuration objects without polluting each other" do c1 = Pancake::Configuration.make c2 = Pancake::Configuration.make c1.default :foo, :bar c2.default :foo, :baz, "A description of foo" c1i, c2i = c1.new, c2.new c1i.foo.should == :bar c1i.defaults[:foo][:value].should == :bar c1i.defaults[:foo][:description].should == "" c2i.foo.should == :baz c2i.defaults[:foo][:value].should == :baz c2i.defaults[:foo][:description].should == "A description of foo" end it "should allow me to define defaults in the make block" do c1 = Pancake::Configuration.make do default :foo, :bar, "Foo Desc" default :baz, 42, "The Answer" end c = c1.new c.foo.should == :bar c.baz.should == 42 end it "should overwrite the default values" do @Conf.default :foo, :bar c = @Conf.new c.foo = :baz c.foo.inspect c.foo.should == :baz c.defaults[:foo][:value].should == :bar end it "should not add a default value for values I set blindly" do c = @Conf.new c.bar.should be_nil c.defaults.keys.should_not include(:bar) end it "should allow me to set a value then the default and not get mixed up" do c = @Conf.new c.bar = :foo c.defaults[:bar][:value].should == nil end it "should let me declare defaults after I've initizlied the configuartion object" do c = @Conf.new @Conf.default :foo, :bar c.foo.should == :bar end it "should give me a list of the current defaults" do @Conf.default :foo, :bar @Conf.default :bar, :baz, "Some description" c = @Conf.new c.defaults.should == { :foo => { :description => "", :value => :bar }, :bar => { :description => "Some description", :value => :baz } } end it "should give me a description for a default" do @Conf.default :foo, :bar, "foo description" c = @Conf.new c.description_for(:foo).should == "foo description" end it "should give me a list of values for the current object" do @Conf.default :foo, :bar c = @Conf.new c.values.should == {} c.foo c.values.should == {:foo => :bar} c.baz = :paz c.values.should == {:foo => :bar, :baz => :paz} end it "should allow me to define methods in the make block" do c = Pancake::Configuration.make do default :foo, :bar default :bar do foobar end def foobar "This is in foobar" end end ci = c.new ci.foo.should == :bar ci.bar.should == "This is in foobar" end it "should not cache the default when it's defined in a block" do c = Pancake::Configuration.make do default :foo do bar end default :bar, :bar end ci = c.new ci.foo.should == :bar ci.bar = :baz ci.bar.should == :baz ci.foo.should == :baz end it "should overwrite the proc when set directly" do @Conf.default :foo, :foo @Conf.default(:bar){ foo } ci = @Conf.new ci.bar.should == :foo ci.foo = :baz ci.bar.should == :baz ci.bar = :foobar ci.bar.should == :foobar end it "should not cache nil when accessing before defaults are set" do c = @Conf.new c.foo.should be_nil @Conf.default :foo, :bar c.foo.should == :bar c.foo = :baz c.foo.should == :baz end end end describe "pancake configuartion" do it "should provide access to it's configuration object" do Pancake.configuration.class.should inherit_from(Pancake::Configuration::Base) end end
hassox/pancake
lib/pancake/core_ext/object.rb
class Object extend ::Pancake::Hooks::InheritableInnerClasses end # Vendored from http://eigenclass.org/hiki/instance_exec # 2009-06-02 # Adapted for ruby 1.9 where the method is deinfed on Object unless Object.method_defined?(:instance_exec) class Object # Like instace_eval but allows parameters to be passed. def instance_exec(*args, &block) mname = "__instance_exec_#{Thread.current.object_id.abs}_#{object_id.abs}" Object.class_eval{ define_method(mname, &block) } begin ret = send(mname, *args) ensure Object.class_eval{ undef_method(mname) } rescue nil end ret end end end
hassox/pancake
lib/pancake/generators.rb
<reponame>hassox/pancake<gh_stars>1-10 require 'thor' require 'thor/group' Dir[File.join(File.dirname(__FILE__), "generators", "*.rb")].each do |f| require f unless f == 'base.rb' end
hassox/pancake
spec/pancake/middlewares/logger_spec.rb
require 'spec_helper' describe Pancake::Middlewares::Logger do before do Pancake.stack(:logger).use(Pancake::Middlewares::Logger) class ::PancakeSpecLogger def self.call(env) Rack::Response.new("OK").finish end end end after do clear_constants :PancakeSpecLogger FileUtils.rm_rf(File.join(Pancake.get_root(__FILE__), "log")) end def app Pancake.start(:root => Pancake.get_root(__FILE__)){ PancakeSpecLogger } end it "should inject a logger into the request env" do the_app = app env = Rack::MockRequest.env_for("/") env['rack.logger'].should be_nil the_app.call(env) env['rack.logger'].class.should == Pancake::Logger end end
hassox/pancake
spec/pancake/fixtures/tasks/root2/tasks/task2.rake
$captures << "root2/tasks/task2.rake"
hassox/pancake
lib/pancake/defaults/middlewares.rb
Pancake.stack(:logger).use(Pancake::Middlewares::Logger)
hassox/pancake
lib/pancake/middleware.rb
module Pancake # Provides a mixin to use on any class to give it middleware management capabilities. # This module provides a rich featureset for defining a middleware stack. # # Middlware can be set before, or after other middleware, can be tagged / named, # and can be declared to only be active in certain types of stacks. module Middleware # When extending a base class with the Pancake::Middleware, # an inner class StackMiddleware is setup on the base class. # This inner class is where all the inforamation is stored on the stack to be defined # The inner StackMiddleware class is also set to be inherited # with the base class (and all children classes) # So that each class gets its own copy and may maintain the base # stack from the parent, but edit it in the child. def self.extended(base) base.class_eval <<-RUBY class StackMiddleware < Pancake::Middleware::StackMiddleware; end RUBY if base.is_a?(Class) base.inheritable_inner_classes :StackMiddleware end super end # self.extended # Build a middleware stack given an application and some middleware classes # # @param [Object] app a rack application to wrap in the middlware list # @param [Array<StackMiddleware>] mwares an array of # StackMiddleware instances where each instance # defines a middleware to use in constructing the stack # # @example # Pancake::Middleware.build(@app, [MWare_1, MWare_2]) # @return [Object] # An application instance of the first middleware defined in the array # The application should be an instance that conforms to Rack specifications # # @api public # @since 0.1.0 # @author <NAME> def self.build(app, mwares) mwares.reverse.inject(app) do |a, m| m.middleware.new(a, *m.args, &m.block) end end # @param [Array<Symbol>] labels An array of labels specifying the stack labels to use to build the middlware list # # @return [Array<StackMiddleware>] # An array of middleware specifications in the order they should be used to wrap the application # # @see Pancake::Middleware::StackMiddleware # @api public # @since 0.1.0 # @author <NAME> def middlewares self::StackMiddleware.middlewares end # Useful for adding additional information into your middleware stack definition # # @param [Object] name # The name of a given middleware. Each piece of middleware has a name in the stack. # By naming middleware we can refer to it later, swap it out for a different class or even just remove it from the stack. # @param [Hash] opts An options hash # @option opts [Object] :before # Sets this middlware to be run after the middleware named. Name is either the name given to the # middleware stack, or the Middleware class itself. # @option opts [Object] :after # Sets this middleware to be run after the middleware name. Name is either the name given to the # middleware stack or the Middleware class itself. # # @example Declaring un-named middleware via the stack # MyClass.stack.use(MyMiddleware) # # This middleware will be named MyMiddleware, and can be specified with (:before | :after) => MyMiddleware # # @example Declaring a named middleware via the stack # MyClass.stack(:foo).use(MyMiddleware) # # This middleware will be named :foo and can be specified with (:before | :after) => :foo # # @example Declaring a named middleware with a :before key # MyClass.stack(:foo, :before => :bar).use(MyMiddleware) # # This middleware will be named :foo and will be run before the middleware named :bar # If :bar is not run, :foo will not be run either # # @example Declaring a named middlware with an :after key # MyClass.stack(:foo, :after => :bar).use(MyMiddleware) # # This middleware will be named :foo and will be run after the middleware named :bar # If :bar is not run, :foo will not be run either # # @see Pancake::Middleware#use # @api public # @since 0.1.0 # @author <NAME> def stack(name = nil, opts = {}) if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name] unless mw.stack == self mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup end mw else self::StackMiddleware.new(name, self, opts) end end # Adds middleware to the current stack definition # # @param [Class] middleware The middleware class to use in the stack # @param [Hash] opts An options hash that is passed through to the middleware when it is instantiated # # @yield The block is provided to the middlewares #new method when it is initialized # # @example Bare use call # MyApp.use(MyMiddleware, :some => :option){ # middleware initialization block here } # # @example Use call after a stack call # MyApp.stack(:foo).use(MyMiddleware, :some => :option){ # middleware initialization block here } # # @see Pancake::Middleware#stack # @api public # @since 0.1.0 # @author <NAME> def use(middleware, *_args, &block) stack(middleware).use(middleware, *_args, &block) end # use # StackMiddleware manages the definition of the middleware stack for a given class. # It's instances are responsible for the definition of a single piece of middleware, and the class # is responsible for specifying the full stack for a given class. # # When Pancake::Middleware extends a class, an inner class is created in that class called StackMiddleware. # That StackMiddleware class inherits from Pancake::Middleware::StackMiddleware. # # @example The setup when Pancake::Middleware is extended # MyClass.extend Pancake::Middleware # # sets up # # class MyClass # class StackMiddleware < Pancake::Middleware::StackMiddleware; end # end # # This is then set is an inheritable inner class on the extended class, such that when it is inherited, # the StackMiddleware class is inherited to an inner class of the same name on the child. class StackMiddleware # @api private extlib_inheritable_reader :_central_mwares, :_mwares, :_before, :_after @_central_mwares, @_before, @_after, @_mwares = [], {}, {}, {} # @api private attr_reader :middleware, :name # @api private attr_accessor :args, :block, :stack, :options class << self def use(mware, *_args, &block) new(mware).use(mware, *_args, &block) end # Resets this stack middlware. Useful for specs def reset! _central_mwares.clear _mwares.clear _before.clear _after.clear end # Get the middleware list for this StackMiddleware # # @return [Array<StackMiddleware>] # An array of the middleware definitions to use in the order that they should be applied # Takes into account all :before, :after settings and only constructs the stack where # the labels are applied # # @see Pancake.stack_labels for a description on stack labels # @api public # @since 0.1.0 # @author <NAME> def middlewares _central_mwares.map do |name| map_middleware(name) end.flatten end # Map the middleware for a given <name>ed middleware. Applies the before and after groups of middlewares # # @param [Object] name The name of the middleware to map the before and after groups to # @return [Array<StackMiddleware>] # Provides an array of StackMiddleware instances in the array [<before :foo>, <:foo>, <after :foo>] # # @api private # @since 0.1.0 # @author <NAME> def map_middleware(name) result = [] _before[name] ||= [] _after[name] ||= [] result << _before[name].map{|n| map_middleware(n)} result << _mwares[name] result << _after[name].map{|n| map_middleware(n)} result.flatten end # Provides access to a named middleware # # @param [Object] name The name of the defined middleware # # @return [StackMiddleware] The middleware definition associated with <name> # # @api public # @since 0.1.0 # @author <NAME> def [](name) _mwares[name] end end # Provides access to a named middleware # # @see Pancake::Middleware::StackMiddleware.[] for an explaination # @since 0.1.0 # @author <NAME> def [](name) self.class._mwares[name] end # @param [Object] name a name for this middleware definition. Usually a symbol, but could be the class. # @param [Object] stack the stack owner of this middleware. # @param [Hash] options an options hash. Provide labels for this middleware. # @option options [Object] :before A middleware name to add this middleware before # @option options [Object] :after A middleware name to add this middleware after # # @see Pancake::Middleware.stack_labels # @api private # @author <NAME> def initialize(name, stack, options = {}) @name, @stack, @options = name, stack, options end # Delete this middleware from the current stack # # @api public # @since 0.1.0 # @author <NAME> def delete! self.class._mwares.delete(name) self.class._before.delete(name) self.class._after.delete(name) self.class._central_mwares.delete(name) self end # Specify the actual middleware definition to use # # @param [Class] mware A Middleware class to use. This should be a class of Middleware which conforms to the Rack spec # @param [Hash] config A configuration hash to give to the middleware class on initialization # @yield The block is passed to the middleware on initialization # # @see Pancake::Middleware.use # @api public # @since 0.1.0 # @author <NAME> def use(mware, *_args, &block) @middleware, @args, @block = mware, _args, block @name = @middleware if name.nil? if options[:before] raise "#{options[:before].inspect} middleware is not defined for this stack" unless self.class._mwares.keys.include?(options[:before]) self.class._before[options[:before]] ||= [] self.class._before[options[:before]] << name elsif options[:after] raise "#{options[:after].inspect} middleware is not defined for this stack" unless self.class._mwares.keys.include?(options[:after]) self.class._after[options[:after]] ||= [] self.class._after[options[:after]] << name else self.class._central_mwares << name unless self.class._central_mwares.include?(name) end self.class._mwares[name] = self self end # @api private def dup result = super result.args = result.args.map{|element| element.dup} result.options = result.options.dup result end end end # Middleware end # Pancake
hassox/pancake
lib/pancake/mixins/render.rb
<reponame>hassox/pancake require 'pancake/mixins/render/template' require 'pancake/mixins/render/view_context' module Pancake module Mixins module Render class TemplateNotFound < Pancake::Errors::NotFound; end RENDER_SETUP = lambda do |base| base.class_eval do extend Pancake::Mixins::Render::ClassMethods include Pancake::Mixins::Render::InstanceMethods class base::ViewContext < Pancake::Mixins::Render::ViewContext; end inheritable_inner_classes :ViewContext unless ancestors.include?(Pancake::Paths) extend Pancake::Paths end end end def self.included(base) RENDER_SETUP.call(base) end module ClassMethods def _template_cache @_template_cache ||= {} end # Allows you to set path label for the templates for this class # # @example # MyClass.push_paths(:my_templates, "somewhere", "**/*") # # MyClass._template_path_name #=> :my_templates # @api public def _template_path_name(opts = {}) opts[:template_path_name] || :views end def _find_template(name, opts = {}) template(name, opts) end def _view_context_cache @_view_context_cache ||= {} @_view_context_cache end def _find_view_context_class_for(template) _view_context_cache[template] ||= begin self::ViewContext end _view_context_cache[template] end def _renderer_and_view_context_class_for(tplate) [template(tplate), _find_view_context_class_for(tplate)] end def _template_name_for(name, opts) "#{name}" end def template(name, opts = {}) case name when Template name when String, Symbol template_names = case __template = _template_name_for(name, opts) when String, Symbol [__template] when Array __template when Proc [__template.call(opts)].flatten else nil end renderer = _template_cache[template_names] return renderer if renderer unique_paths = unique_paths_for(_template_path_name(opts), :invert => true) renderer_path = nil template_name = nil template_names.detect do |tn| unique_paths.detect do |path| if path.last =~ %r[^\/?(#{tn})\.\w+$] template_name = tn renderer_path = path.join end end end raise TemplateNotFound unless renderer_path _template_cache[template_names] = Template.new(template_name, self, renderer_path) else nil end end def base_template_name :base end end # ClassMethods module InstanceMethods def render(*args) opts = Hash === args.last ? args.pop : {} name = args.shift template = self.class.template(name, opts) return opts[:text] if opts[:text] # Get the view context for the tempalte template, vc_class = self.class._renderer_and_view_context_class_for(template) yield v if block_given? view_context = vc_class.new(self) view_context_before_render(view_context) view_context.render(template, opts) end def partial(*args) opts = Hash === args.last ? args.pop : {} opts = opts.dup name = args.shift with = opts.delete(:with) as = opts.delete(:as) partial_name = _partial_template_name_for(name, opts) # Get the view context for the tempalte template, vc_class = self.class._renderer_and_view_context_class_for(partial_name) view_context = vc_class.new(self) view_context_before_render(view_context) out = "" if with.kind_of?(Array) with.each do |item| as.nil? ? (opts[name] = item) : (opts[as] = item) out << view_context.render(template, opts) end else as.nil? ? (opts[name] = with) : (opts[as] = with) out << view_context.render(template, opts) end out end def template(name_or_template, opts = {}) self.class.template(name_or_template, opts) end # A place holder method for any implementor that wants # to configure the view context prior to rendering occuring # any time this method is overwritten, it should call super! # # @api overwritable def view_context_before_render(context) end private # @api_overwritable def _template_name_for(name, opts = {}) self.class._template_name_for(name, opts) end def _partial_template_name_for(name, opts) "_#{name}" end end # InstanceMethods end # Render end # Mixins end # Pancake
andreteodoro/secret_friend
db/migrate/20180122191711_add_date_to_campaign.rb
class AddDateToCampaign < ActiveRecord::Migration[5.0] def change add_column :campaigns, :event_date, :datetime add_column :campaigns, :event_hour, :string add_column :campaigns, :locale, :string end end
andreteodoro/secret_friend
spec/factories/member.rb
<filename>spec/factories/member.rb FactoryGirl.define do factory :member do name { FFaker::Lorem.word } email { FFaker::Internet.email } campaign end end
andreteodoro/secret_friend
app/mailers/campaign_mailer.rb
class CampaignMailer < ApplicationMailer def raffle(campaign, member, friend) @campaign = campaign @member = member @friend = friend mail to: @member.email, subject: "Nosso Amigo Secreto: #{@campaign.title}" end end
andreteodoro/secret_friend
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery with: :exception rescue_from ActiveRecord::RecordNotFound, :with => :render_404 def render_404 redirect_to main_app.root_url end end
andreteodoro/secret_friend
app/models/campaign.rb
<reponame>andreteodoro/secret_friend class Campaign < ApplicationRecord belongs_to :user has_many :members, dependent: :destroy before_validation :set_member, on: :create before_validation :set_status, on: :create enum status: [:pending, :finished] validates :title, :description, :user, :status, presence: true def count_opened members.where(open: true).count end private def set_status self.status = :pending end def set_member members << Member.create(name: user.name, email: user.email) end end
andreteodoro/secret_friend
spec/factories/campaign.rb
<reponame>andreteodoro/secret_friend<filename>spec/factories/campaign.rb FactoryGirl.define do factory :campaign do title { FFaker::Lorem.word } description { FFaker::Lorem.sentence } user status { :pending } locale { "#{FFaker::Address.city}, #{FFaker::Address.street_address}"} event_date { FFaker::Time.date } event_hour { rand(24).to_s } end end
andreteodoro/secret_friend
config/routes.rb
require 'sidekiq/web' Rails.application.routes.draw do devise_for :users, :controllers => { registrations: 'registrations' } #mount Sidekiq::Web => '/sidekiq' root to: 'pages#home' resources :campaigns, except: [:new] do post 'raffle', on: :member # post 'raffle', on: :collection end get 'members/:token/opened', to: 'members#opened' resources :members, only: [:create, :destroy, :update] end
kenjij/firebase-ruby
lib/firebase-ruby.rb
<filename>lib/firebase-ruby.rb require 'firebase-ruby/logger' require 'firebase-ruby/database' require 'firebase-ruby/auth'
kenjij/firebase-ruby
lib/firebase-ruby/version.rb
<filename>lib/firebase-ruby/version.rb module Firebase Version = '0.3.1' end
kenjij/firebase-ruby
lib/firebase-ruby/auth.rb
<filename>lib/firebase-ruby/auth.rb<gh_stars>1-10 require 'jwt' require 'firebase-ruby/neko-http' module Firebase class Auth GOOGLE_JWT_SCOPE = 'https://www.googleapis.com/auth/firebase.database https://www.googleapis.com/auth/userinfo.email' GOOGLE_JWT_AUD = 'https://oauth2.googleapis.com/token' GOOGLE_ALGORITHM = 'RS256' GOOGLE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer' GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token' attr_reader :project_id attr_reader :client_email attr_reader :token_uri attr_reader :access_token attr_reader :expires # Creates Firebase OAuth based auth object; one argument must be specified def initialize(json: nil, path: nil) if json load_privatekeyjson(json) elsif path load_privatekeyfile(path) end end # Return a valid access token; it will retrieve a new token if necessary def valid_token return access_token if access_token && !expiring? return access_token if request_access_token raise 'No valid access token.' end # If token is expiring within a minute def expiring? return true if expires - Time.now < 60 return false end # If token has already expired def expired? return true if expires - Time.now <= 0 return false end private # @param json [String] JSON with private key def load_privatekeyjson(json) raise ArgumentError, 'private key JSON missing' unless json cred = JSON.parse(json, {symbolize_names: true}) @private_key = cred[:private_key] @project_id = cred[:project_id] @client_email = cred[:client_email] @token_uri = cred[:token_uri] @token_uri ||= GOOGLE_TOKEN_URL Firebase.logger.info('Private key loaded from JSON') s = [:project_id, :client_email].map{ |x| "#{x}: #{self.public_send(x)}" } Firebase.logger.debug("The key contained:\n#{s.join("\n")}") end # @param path [String] path to JSON file with private key def load_privatekeyfile(path) raise ArgumentError, 'private key file path missing' unless path Firebase.logger.debug("Loading private key file: #{path}") load_privatekeyjson(IO.read(path)) end # Request new token from Google def request_access_token Firebase.logger.info('Requesting access token...') Firebase.logger.debug("token_uri: #{token_uri}") res = Neko::HTTP.post_form(token_uri, jwt) Firebase.logger.debug("HTTP response code: #{res[:code]}") if res.class == Hash && res[:code] == 200 data = JSON.parse(res[:body], {symbolize_names: true}) @access_token = data[:access_token] @expires = Time.now + data[:expires_in] Firebase.logger.info('Access token acquired.') s = "Token #{@access_token.length} bytes, expires #{@expires}" Firebase.logger.debug(s) return true else Firebase.logger.error('Access token request failed.') Firebase.logger.debug("HTTP #{res[:code]} #{res[:message]}") end return false end # Generate JWT claim def jwt pkey = OpenSSL::PKey::RSA.new(@private_key) now_ts = Time.now.to_i payload = { iss: client_email, scope: GOOGLE_JWT_SCOPE, aud: GOOGLE_JWT_AUD, iat: now_ts, exp: now_ts + 60 } jwt = JWT.encode payload, pkey, GOOGLE_ALGORITHM return {grant_type: GOOGLE_GRANT_TYPE, assertion: jwt} end end end
kenjij/firebase-ruby
lib/firebase-ruby/database.rb
<gh_stars>1-10 require 'firebase-ruby/neko-http' module Firebase class Database FIREBASE_URL_TEMPLATE = 'https://%s.firebaseio.com/' attr_accessor :auth, :print, :shallow def initialize() end def set_auth_with_key(json: nil, path: nil) @auth = Auth.new(json: json, path: path) end def project_id=(id) @project_id = id end def project_id return @project_id if @project_id return auth.project_id if auth return nil end def get(path) return operate(__method__, path) end def put(path, data) return operate(__method__, path, data) end def patch(path, data) return operate(__method__, path, data) end def post(path, data) return operate(__method__, path, data) end def delete(path) return operate(__method__, path) end private def operate(method, path, data = nil) case method when :get, :delete res_data = http.public_send(method, path: format_path(path)) when :put, :patch, :post data = JSON.fast_generate(data) if data.class == Hash res_data = http.public_send(method, path: format_path(path), body: data) end return handle_response_data(res_data) end def http unless @http url = FIREBASE_URL_TEMPLATE % project_id @http = Neko::HTTP.new(url, {'Content-Type' => 'application/json'}) end @http.headers['Authorization'] = "Bearer #{auth.valid_token}" return @http end def format_path(path) path = '/' + path unless path.start_with?('/') return path + '.json' end def handle_response_data(data) if data[:code] != 200 Firebase.logger.error("HTTP response error: #{data[:code]}\n#{data[:message]}") return nil end return JSON.parse(data[:body], {symbolize_names: true}) end end end
kenjij/firebase-ruby
firebase-ruby.gemspec
$LOAD_PATH.unshift(File.expand_path('../lib', __FILE__)) require 'firebase-ruby/version' Gem::Specification.new do |s| s.name = 'firebase-ruby' s.version = Firebase::Version s.authors = ['<NAME>.'] s.email = ['<EMAIL>'] s.summary = %q{Pure simple Ruby based Firebase REST library} s.description = %q{A pure Ruby server-side library for Firebase Realtime Database with only one external dependency: jwt.} s.homepage = 'https://github.com/kenjij/firebase-ruby' s.license = 'MIT' s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.require_paths = ['lib'] s.required_ruby_version = '>= 2.1' s.add_runtime_dependency 'jwt', '~> 2.2' end
marketplacer/jquery-rjs
lib/jquery-rjs/on_load_action_view.rb
<gh_stars>1-10 require 'action_view/helpers/jquery_helper' require 'action_view/helpers/jquery_ui_helper' require 'action_view/template/handlers/rjs' require 'jquery-rjs/javascript_helper' require 'jquery-rjs/rendering' ActionView::Base.class_eval do cattr_accessor :debug_rjs self.debug_rjs = false end ActionView::Base.class_eval do include ActionView::Helpers::JqueryHelper include ActionView::Helpers::JqueryUiHelper end ActionView::TestCase.class_eval do include ActionView::Helpers::JqueryHelper include ActionView::Helpers::JqueryUiHelper end ActionView::Template.register_template_handler :rjs, ActionView::Template::Handlers::RJS.new
marketplacer/jquery-rjs
lib/jquery-rjs.rb
require 'rails' require 'active_support' module JqueryRjs class Engine < Rails::Engine initializer 'jquery-rjs.initialize' do ActiveSupport.on_load(:action_controller) do require 'jquery-rjs/on_load_action_controller' end ActiveSupport.on_load(:action_view) do require 'jquery-rjs/on_load_action_view' end end end end
marketplacer/jquery-rjs
test/controller/new_base/render_rjs_test.rb
<gh_stars>1-10 require 'abstract_unit' module RenderRjs class BasicController < ActionController::Base layout "application", :only => :index_respond_to self.view_paths = [ActionView::FixtureResolver.new( "layouts/application.html.erb" => "", "render_rjs/basic/index.js.rjs" => "page[:customer].replace_html render(:partial => 'customer')", "render_rjs/basic/index_html.js.rjs" => "page[:customer].replace_html :partial => 'customer'", "render_rjs/basic/index_no_js.js.erb" => "<%= render(:partial => 'developer') %>", "render_rjs/basic/_customer.js.erb" => "JS Partial", "render_rjs/basic/_customer.html.erb" => "HTML Partial", "render_rjs/basic/_developer.html.erb" => "HTML Partial", "render_rjs/basic/index_locale.js.rjs" => "page[:customer].replace_html :partial => 'customer'", "render_rjs/basic/_customer.da.html.erb" => "Danish HTML Partial", "render_rjs/basic/_customer.da.js.erb" => "Danish JS Partial" )] def index render end def index_respond_to respond_to do |format| format.js { render :action => "index_no_js" } end end def index_locale self.locale = :da end end class TestBasic < Rack::TestCase testing BasicController def setup @old_locale = I18n.locale end def teardown I18n.locale = @old_locale end test "rendering a partial in an RJS template should pick the JS template over the HTML one" do get :index, "format" => "js" assert_response("$(\"#customer\").html(\"JS Partial\");") end test "rendering a partial in an RJS template should pick the HTML one if no JS is available" do get :index_no_js, "format" => "js" assert_response("HTML Partial") end test "rendering a partial in an RJS template should pick the HTML one if no JS is available on respond_to" do get :index_respond_to, "format" => "js" assert_response("HTML Partial") end test "replacing an element with a partial in an RJS template should pick the HTML template over the JS one" do get :index_html, "format" => "js" assert_response("$(\"#customer\").html(\"HTML Partial\");") end test "replacing an element with a partial in an RJS template with a locale should pick the localed HTML template" do get :index_locale, "format" => "js" assert_response("$(\"#customer\").html(\"Danish HTML Partial\");") end end end
marketplacer/jquery-rjs
lib/jquery-rjs/on_load_action_controller.rb
<reponame>marketplacer/jquery-rjs require 'jquery-rjs/selector_assertions' require 'jquery-rjs/renderers'
panmari/flutterfire
packages/firebase_core/firebase_core/ios/firebase_sdk_version.rb
<filename>packages/firebase_core/firebase_core/ios/firebase_sdk_version.rb<gh_stars>1-10 def firebase_sdk_version!() '7.3.0' end
eric/github-services
services/basecamp.rb
service :basecamp do |data, payload| repository = payload['repository']['name'] name_with_owner = File.join(payload['repository']['owner']['name'], repository) branch = payload['ref'].split('/').last basecamp = Basecamp.new(data['url'], data['username'], data['password']) project_id = basecamp.projects.select { |p| p.name.downcase == data['project'].downcase }.first.id category_id = basecamp.message_categories(project_id).select { |category| category.name.downcase == data['category'].downcase }.first.id payload['commits'].each do |commit| gitsha = commit['id'] short_git_sha = gitsha[0..5] timestamp = Date.parse(commit['timestamp']) added = commit['added'].map { |f| ['A', f] } removed = commit['removed'].map { |f| ['R', f] } modified = commit['modified'].map { |f| ['M', f] } changed_paths = (added + removed + modified).sort_by { |(char, file)| file } changed_paths = changed_paths.collect { |entry| entry * ' ' }.join("\n ") # Shorten the elements of the subject commit_title = commit['message'][/^([^\n]+)/, 1] if commit_title.length > 50 commit_title = commit_title.slice(0,50) << '...' end title = "Commit on #{name_with_owner}: #{short_git_sha}: #{commit_title}" body = <<-EOH *Date:* #{timestamp} (#{timestamp.strftime('%a, %d %b %Y')}) *Author:* #{commit['author']['name']} <#{commit['author']['email']}> *Commit:* <a href="#{commit['url']}">#{gitsha}</a> *Branch:* #{branch} *Home:* #{payload['repository']['url']} h2. Log Message <pre>#{commit['message']}</pre> EOH if changed_paths.size > 0 body << <<-EOH h2. Changed paths <pre> #{changed_paths}</pre> EOH end basecamp.post_message(project_id, :title => title, :body => body, :category_id => category_id) end end
earlino727/byebug
test/commands/display_test.rb
<reponame>earlino727/byebug require 'test_helper' module Byebug # # Tests displaying values of expressions on every stop. # class DisplayTest < TestCase def program strip_line_numbers <<-EOC 1: module Byebug 2: d = 0 3: 4: byebug 5: 6: d += 3 7: d + 6 8: end EOC end def test_shows_expressions enter 'display d + 1' debug_code(program) { clear_displays } check_output_includes '1: d + 1 = 1' end def test_shows_undefined_expressions enter 'display e' debug_code(program) { clear_displays } check_output_includes '1: e = (undefined)' end def test_saves_displayed_expressions enter 'display d + 1' debug_code(program) do assert_equal [[true, 'd + 1']], Byebug.displays clear_displays end end def test_displays_all_expressions_available enter 'display d', 'display d + 1', 'display' debug_code(program) { clear_displays } check_output_includes '1: d = 0', '2: d + 1 = 1' end end end
earlino727/byebug
.git-hooks/pre_commit/c_cop.rb
<filename>.git-hooks/pre_commit/c_cop.rb<gh_stars>1-10 # # Custom pre-commit hook to check C-code style # module Overcommit module Hook module PreCommit # # Inherit from base hook # class CCop < Base # # Implement overcommit's interface # def run missing_requirements = check_for_executable return [:fail, missing_requirements] if missing_requirements offenses = 0 applicable_files.each do |file| res = execute([required_executable, file, '-o', "#{file}_"]) unchanged = FileUtils.compare_file(file, "#{file}_") if res.success? offenses += 1 unless unchanged FileUtils.rm_f("#{file}_") end return :pass if offenses.zero? file_list = applicable_files.join(' ') [:fail, "#{offenses} errors found. Run `indent #{file_list}`"] end end end end end