Repository: shageman/the_next_big_thing Branch: master Commit: 7fe6d7fbf8de Files: 245 Total size: 143.7 KB Directory structure: gitextract_eb0mmh5t/ ├── .gitignore ├── .rspec ├── .ruby-gemset ├── .ruby-version ├── .travis.yml ├── Gemfile ├── MIT-LICENSE ├── README.md ├── Rakefile ├── bin/ │ ├── bundle │ ├── rails │ └── rake ├── build.sh ├── components/ │ ├── annoyance/ │ │ ├── .gitignore │ │ ├── .rspec │ │ ├── .ruby-gemset │ │ ├── .ruby-version │ │ ├── Gemfile │ │ ├── MIT-LICENSE │ │ ├── README.rdoc │ │ ├── Rakefile │ │ ├── annoyance.gemspec │ │ ├── app/ │ │ │ └── models/ │ │ │ └── annoyance/ │ │ │ ├── levels.rb │ │ │ └── meter.rb │ │ ├── lib/ │ │ │ ├── annoyance/ │ │ │ │ ├── engine.rb │ │ │ │ └── version.rb │ │ │ └── annoyance.rb │ │ ├── spec/ │ │ │ ├── annoyance/ │ │ │ │ ├── levels_spec.rb │ │ │ │ └── meter_spec.rb │ │ │ └── spec_helper.rb │ │ └── test.sh │ ├── email_signup/ │ │ ├── .gitignore │ │ ├── .rspec │ │ ├── .ruby-gemset │ │ ├── .ruby-version │ │ ├── Gemfile │ │ ├── MIT-LICENSE │ │ ├── README.rdoc │ │ ├── Rakefile │ │ ├── app/ │ │ │ └── models/ │ │ │ └── email_signup/ │ │ │ ├── entry.rb │ │ │ └── entry_manager.rb │ │ ├── config/ │ │ │ └── routes.rb │ │ ├── db/ │ │ │ └── migrate/ │ │ │ ├── 20130331124429_create_news_signup_entry.rb │ │ │ ├── 20130331134505_rename_news_signup_etnries_to_email_signup_entries.rb │ │ │ └── 20130403220851_remove_tries_from_email_signup_entry.rb │ │ ├── email_signup.gemspec │ │ ├── lib/ │ │ │ ├── email_signup/ │ │ │ │ ├── engine.rb │ │ │ │ └── version.rb │ │ │ ├── email_signup.rb │ │ │ └── tasks/ │ │ │ └── news_signup_tasks.rake │ │ ├── script/ │ │ │ └── rails │ │ ├── spec/ │ │ │ ├── dummy/ │ │ │ │ ├── README.rdoc │ │ │ │ ├── Rakefile │ │ │ │ ├── app/ │ │ │ │ │ ├── assets/ │ │ │ │ │ │ ├── javascripts/ │ │ │ │ │ │ │ └── application.js │ │ │ │ │ │ └── stylesheets/ │ │ │ │ │ │ └── application.css │ │ │ │ │ ├── controllers/ │ │ │ │ │ │ └── application_controller.rb │ │ │ │ │ ├── helpers/ │ │ │ │ │ │ └── application_helper.rb │ │ │ │ │ ├── mailers/ │ │ │ │ │ │ └── .gitkeep │ │ │ │ │ ├── models/ │ │ │ │ │ │ └── .gitkeep │ │ │ │ │ └── views/ │ │ │ │ │ └── layouts/ │ │ │ │ │ └── application.html.erb │ │ │ │ ├── config/ │ │ │ │ │ ├── application.rb │ │ │ │ │ ├── boot.rb │ │ │ │ │ ├── database.yml │ │ │ │ │ ├── environment.rb │ │ │ │ │ ├── environments/ │ │ │ │ │ │ ├── development.rb │ │ │ │ │ │ ├── production.rb │ │ │ │ │ │ └── test.rb │ │ │ │ │ ├── initializers/ │ │ │ │ │ │ ├── backtrace_silencers.rb │ │ │ │ │ │ ├── inflections.rb │ │ │ │ │ │ ├── mime_types.rb │ │ │ │ │ │ ├── secret_token.rb │ │ │ │ │ │ ├── session_store.rb │ │ │ │ │ │ └── wrap_parameters.rb │ │ │ │ │ ├── locales/ │ │ │ │ │ │ └── en.yml │ │ │ │ │ └── routes.rb │ │ │ │ ├── config.ru │ │ │ │ ├── db/ │ │ │ │ │ └── schema.rb │ │ │ │ ├── lib/ │ │ │ │ │ └── assets/ │ │ │ │ │ └── .gitkeep │ │ │ │ ├── log/ │ │ │ │ │ └── .gitkeep │ │ │ │ ├── public/ │ │ │ │ │ ├── 404.html │ │ │ │ │ ├── 422.html │ │ │ │ │ └── 500.html │ │ │ │ └── script/ │ │ │ │ └── rails │ │ │ ├── models/ │ │ │ │ └── email_signup/ │ │ │ │ ├── entry_manager_spec.rb │ │ │ │ └── entry_spec.rb │ │ │ └── spec_helper.rb │ │ └── test.sh │ ├── event_counter/ │ │ ├── .gitignore │ │ ├── .rspec │ │ ├── .ruby-gemset │ │ ├── .ruby-version │ │ ├── Gemfile │ │ ├── MIT-LICENSE │ │ ├── README.rdoc │ │ ├── Rakefile │ │ ├── app/ │ │ │ └── models/ │ │ │ └── event_counter/ │ │ │ └── logger.rb │ │ ├── config/ │ │ │ └── routes.rb │ │ ├── db/ │ │ │ └── migrate/ │ │ │ └── 20130403021547_create_event_counter_count.rb │ │ ├── event_counter.gemspec │ │ ├── lib/ │ │ │ ├── event_counter/ │ │ │ │ ├── engine.rb │ │ │ │ ├── test_helper.rb │ │ │ │ └── version.rb │ │ │ ├── event_counter.rb │ │ │ └── tasks/ │ │ │ └── event_counter_tasks.rake │ │ ├── script/ │ │ │ └── rails │ │ ├── spec/ │ │ │ ├── dummy/ │ │ │ │ ├── README.rdoc │ │ │ │ ├── Rakefile │ │ │ │ ├── app/ │ │ │ │ │ ├── assets/ │ │ │ │ │ │ ├── javascripts/ │ │ │ │ │ │ │ └── application.js │ │ │ │ │ │ └── stylesheets/ │ │ │ │ │ │ └── application.css │ │ │ │ │ ├── controllers/ │ │ │ │ │ │ └── application_controller.rb │ │ │ │ │ ├── helpers/ │ │ │ │ │ │ └── application_helper.rb │ │ │ │ │ ├── mailers/ │ │ │ │ │ │ └── .gitkeep │ │ │ │ │ ├── models/ │ │ │ │ │ │ └── .gitkeep │ │ │ │ │ └── views/ │ │ │ │ │ └── layouts/ │ │ │ │ │ └── application.html.erb │ │ │ │ ├── config/ │ │ │ │ │ ├── application.rb │ │ │ │ │ ├── boot.rb │ │ │ │ │ ├── database.yml │ │ │ │ │ ├── environment.rb │ │ │ │ │ ├── environments/ │ │ │ │ │ │ ├── development.rb │ │ │ │ │ │ ├── production.rb │ │ │ │ │ │ └── test.rb │ │ │ │ │ ├── initializers/ │ │ │ │ │ │ ├── backtrace_silencers.rb │ │ │ │ │ │ ├── inflections.rb │ │ │ │ │ │ ├── mime_types.rb │ │ │ │ │ │ ├── secret_token.rb │ │ │ │ │ │ ├── session_store.rb │ │ │ │ │ │ └── wrap_parameters.rb │ │ │ │ │ ├── locales/ │ │ │ │ │ │ └── en.yml │ │ │ │ │ └── routes.rb │ │ │ │ ├── config.ru │ │ │ │ ├── db/ │ │ │ │ │ └── schema.rb │ │ │ │ ├── lib/ │ │ │ │ │ └── assets/ │ │ │ │ │ └── .gitkeep │ │ │ │ ├── log/ │ │ │ │ │ └── .gitkeep │ │ │ │ ├── public/ │ │ │ │ │ ├── 404.html │ │ │ │ │ ├── 422.html │ │ │ │ │ └── 500.html │ │ │ │ └── script/ │ │ │ │ └── rails │ │ │ ├── models/ │ │ │ │ └── logger_spec.rb │ │ │ ├── spec_helper.rb │ │ │ └── support/ │ │ │ └── test_helper.rb │ │ └── test.sh │ └── teaser/ │ ├── .gitignore │ ├── .rspec │ ├── .ruby-gemset │ ├── .ruby-version │ ├── Gemfile │ ├── MIT-LICENSE │ ├── README.rdoc │ ├── Rakefile │ ├── app/ │ │ ├── assets/ │ │ │ ├── images/ │ │ │ │ └── teaser/ │ │ │ │ └── .gitkeep │ │ │ ├── javascripts/ │ │ │ │ └── teaser/ │ │ │ │ ├── application.js │ │ │ │ ├── signUp.js │ │ │ │ └── teaser.js │ │ │ └── stylesheets/ │ │ │ └── teaser/ │ │ │ ├── application.css │ │ │ └── teaser.css.scss │ │ ├── controllers/ │ │ │ └── teaser/ │ │ │ ├── application_controller.rb │ │ │ └── tease_controller.rb │ │ └── views/ │ │ ├── layouts/ │ │ │ └── teaser/ │ │ │ └── application.html.erb │ │ └── teaser/ │ │ └── tease/ │ │ └── new.html.haml │ ├── config/ │ │ └── routes.rb │ ├── db/ │ │ └── migrate/ │ │ ├── 20120915205848_create_entry.rb │ │ ├── 20120917081547_add_tries_to_teaser_entries.rb │ │ └── 20130403011500_remove_entry.rb │ ├── lib/ │ │ ├── monkey_patches/ │ │ │ └── engine.rb │ │ ├── tasks/ │ │ │ └── teaser_tasks.rake │ │ ├── teaser/ │ │ │ ├── engine.rb │ │ │ └── version.rb │ │ └── teaser.rb │ ├── script/ │ │ └── rails │ ├── spec/ │ │ ├── controllers/ │ │ │ └── tease_controller_spec.rb │ │ ├── dummy/ │ │ │ ├── README.rdoc │ │ │ ├── Rakefile │ │ │ ├── app/ │ │ │ │ ├── assets/ │ │ │ │ │ ├── javascripts/ │ │ │ │ │ │ └── application.js │ │ │ │ │ └── stylesheets/ │ │ │ │ │ └── application.css │ │ │ │ ├── controllers/ │ │ │ │ │ └── application_controller.rb │ │ │ │ ├── helpers/ │ │ │ │ │ └── application_helper.rb │ │ │ │ ├── mailers/ │ │ │ │ │ └── .gitkeep │ │ │ │ ├── models/ │ │ │ │ │ └── .gitkeep │ │ │ │ └── views/ │ │ │ │ └── layouts/ │ │ │ │ └── application.html.erb │ │ │ ├── config/ │ │ │ │ ├── application.rb │ │ │ │ ├── boot.rb │ │ │ │ ├── database.yml │ │ │ │ ├── environment.rb │ │ │ │ ├── environments/ │ │ │ │ │ ├── development.rb │ │ │ │ │ ├── production.rb │ │ │ │ │ └── test.rb │ │ │ │ ├── initializers/ │ │ │ │ │ ├── backtrace_silencers.rb │ │ │ │ │ ├── inflections.rb │ │ │ │ │ ├── mime_types.rb │ │ │ │ │ ├── secret_token.rb │ │ │ │ │ ├── session_store.rb │ │ │ │ │ └── wrap_parameters.rb │ │ │ │ ├── locales/ │ │ │ │ │ └── en.yml │ │ │ │ └── routes.rb │ │ │ ├── config.ru │ │ │ ├── db/ │ │ │ │ └── schema.rb │ │ │ ├── lib/ │ │ │ │ └── assets/ │ │ │ │ └── .gitkeep │ │ │ ├── log/ │ │ │ │ └── .gitkeep │ │ │ ├── public/ │ │ │ │ ├── 404.html │ │ │ │ ├── 422.html │ │ │ │ └── 500.html │ │ │ ├── script/ │ │ │ │ └── rails │ │ │ ├── teaser_development │ │ │ └── teaser_test │ │ ├── features/ │ │ │ └── signing_up_for_updates_spec.rb │ │ ├── javascripts/ │ │ │ ├── helpers/ │ │ │ │ └── mock-ajax.js │ │ │ ├── support/ │ │ │ │ └── jasmine.yml │ │ │ └── teaser/ │ │ │ └── signup_spec.js │ │ ├── request_spec_helper.rb │ │ ├── spec_helper.rb │ │ └── support/ │ │ └── request_spec_helpers.rb │ ├── teaser.gemspec │ └── test.sh ├── config/ │ ├── application.rb │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── environments/ │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers/ │ │ ├── backtrace_silencers.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── secret_token.rb │ │ ├── session_store.rb │ │ └── wrap_parameters.rb │ ├── locales/ │ │ └── en.yml │ └── routes.rb ├── config.ru ├── db/ │ ├── schema.rb │ └── seeds.rb ├── log/ │ └── .gitkeep ├── migrate_and_prepare_all.sh ├── public/ │ ├── 404.html │ ├── 422.html │ ├── 500.html │ └── robots.txt ├── script/ │ └── rails ├── spec/ │ ├── features/ │ │ └── home_page_spec.rb │ ├── fixtures/ │ │ └── .gitkeep │ └── spec_helper.rb ├── test.sh └── vendor/ ├── assets/ │ ├── javascripts/ │ │ └── .gitkeep │ └── stylesheets/ │ └── .gitkeep └── plugins/ └── .gitkeep ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # See http://help.github.com/ignore-files/ for more about ignoring files. # # If you find yourself ignoring temporary files generated by your text editor # or operating system, you probably want to add a global ignore instead: # git config --global core.excludesfile ~/.gitignore_global # Ignore bundler config .bundle # Ignore the default SQLite database. *.sqlite3 # Ignore all logfiles and tempfiles. */log/*.log log/*.log */tmp tmp .idea .sass-cache .DS_Store ================================================ FILE: .rspec ================================================ --color ================================================ FILE: .ruby-gemset ================================================ tnbt ================================================ FILE: .ruby-version ================================================ 2.1.0 ================================================ FILE: .travis.yml ================================================ gemfile: - Gemfile - components/annoyance/Gemfile - components/email_signup/Gemfile - components/event_counter/Gemfile - components/teaser/Gemfile script: - ./test.sh before_install: - "export DISPLAY=:99.0" - "sh -e /etc/init.d/xvfb start" - cd $(dirname $BUNDLE_GEMFILE) rvm: - 2.1.0 ================================================ FILE: Gemfile ================================================ source "https://rubygems.org" gem "rails", "4.1.8" path 'components' do gem "teaser" end group :test, :development do gem "rspec-rails", "3.1.0" gem "capybara", "2.4.1" gem "sqlite3", "1.3.9" end group :production do gem "pg" end ================================================ FILE: MIT-LICENSE ================================================ Copyright 2012 Stephan Hagemann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # The Next Big Thing [![Build Status](https://secure.travis-ci.org/shageman/the_next_big_thing.png)](https://secure.travis-ci.org/shageman/the_next_big_thing) [![Dependency Status](https://gemnasium.com/shageman/the_next_big_thing.png)](https://gemnasium.com/shageman/the_next_big_thing) [![Code Climate](https://codeclimate.com/github/shageman/the_next_big_thing.png)](https://codeclimate.com/github/shageman/the_next_big_thing) ## What is this? A full-fledged portal to announce the next big thing! Jumpstart the PR campaign for your next big thing by standing on the shoulder of a giant: The next big Thing!! ## What is this really? A sample project showcasing the use of unbuilt Rails Engines and Gems. The entire app has been developed using TDD - follow the commits to see the parts evolve. Current state: * `Teaser` provides the web page one sees when running the the_next_big_thing server. It depends on all the other engines. * `Annoyance` contains a service that given a number will give an indication of how annoying that number is. * `EmailSignup` provides a service allowing the storage of email addresses. * `EventCounter` provides a service that can count for any object how many times a particular action has happened. * The main Rails application does not contain any application code: it does not even have an `app` directory. It is soley responsible for encapsulating and mounting the engine in the right place. ##Resources on component-based Rails applications Twitter hashtag: #cbra - https://twitter.com/hashtag/cbra Blog posts: * http://blog.pivotal.io/pivotal-labs?s=&category=0&post_tag=1505&author=&archives= Past presentations by Ben Smith and me (mostly on this topic) * http://confreaks.com/presenters/790-stephan-hagemann * http://confreaks.com/presenters/784-ben-smith The book I am writing * https://leanpub.com/cbra ## Running the test suite ```bash git clone https://github.com/shageman/the_next_big_thing.git cd the_next_big_thing ./build.sh ``` ## Contributing I highly appreciate it! Fork, pull, create, commit, push, request pull. ## License Copyright (c) 2012-2013 Stephan Hagemann twitter.com/shageman %w(stephan.hagemann gmail.com) * "@" Released under the MIT license. See MIT-LICENSE file for details. ================================================ FILE: Rakefile ================================================ #!/usr/bin/env rake require File.expand_path('../config/application', __FILE__) TheNextBigThing::Application.load_tasks ================================================ FILE: bin/bundle ================================================ #!/usr/bin/env ruby ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) load Gem.bin_path('bundler', 'bundle') ================================================ FILE: bin/rails ================================================ #!/usr/bin/env ruby APP_PATH = File.expand_path('../../config/application', __FILE__) require_relative '../config/boot' require 'rails/commands' ================================================ FILE: bin/rake ================================================ #!/usr/bin/env ruby require_relative '../config/boot' require 'rake' Rake.application.run ================================================ FILE: build.sh ================================================ #!/bin/bash unset BUNDLE_GEMFILE result=0 if [ "$CI" == "true" ]; then BUNDLE_PATH="$HOME/vendor/bundle" fi # Change working directory to this script's parent directory so we find the right files cd "$( dirname "${BASH_SOURCE[0]}" )" for test_script in $(find . -name test.sh); do pushd `dirname $test_script` > /dev/null source "$HOME/.rvm/scripts/rvm" rvm use $(cat .ruby-version)@$(cat .ruby-gemset) --create which ruby rvm gemset name ./test.sh result+=$? popd > /dev/null done if [ $result -eq 0 ]; then echo "SUCCESS" else echo "FAILURE" fi exit $result ================================================ FILE: components/annoyance/.gitignore ================================================ .bundle/ log/*.log pkg/ test/dummy/db/*.sqlite3 test/dummy/log/*.log test/dummy/tmp/ test/dummy/.sass-cache ================================================ FILE: components/annoyance/.rspec ================================================ --color ================================================ FILE: components/annoyance/.ruby-gemset ================================================ tnbtannoyance ================================================ FILE: components/annoyance/.ruby-version ================================================ 2.1.0 ================================================ FILE: components/annoyance/Gemfile ================================================ source "https://rubygems.org" gemspec gem "rspec" ================================================ FILE: components/annoyance/MIT-LICENSE ================================================ Copyright 2012 YOURNAME Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: components/annoyance/README.rdoc ================================================ = Annoyance This project rocks and uses MIT-LICENSE. ================================================ FILE: components/annoyance/Rakefile ================================================ #!/usr/bin/env rake begin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end begin require 'rdoc/task' rescue LoadError require 'rdoc/rdoc' require 'rake/rdoctask' RDoc::Task = Rake::RDocTask end RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'AnnoyanceMeter' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end Bundler::GemHelper.install_tasks require 'rake/testtask' Rake::TestTask.new(:test) do |t| t.libs << 'lib' t.libs << 'test' t.pattern = 'test/**/*_test.rb' t.verbose = false end task :default => :test ================================================ FILE: components/annoyance/annoyance.gemspec ================================================ $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "annoyance/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "annoyance" s.version = Annoyance::VERSION s.authors = ["Stephan Hagemann"] s.email = ["stephan.hagemann@gmail.com"] s.summary = "A very annoyed gem" s.description = "A very annoyed gem" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["spec/**/*"] s.add_development_dependency "rspec", "2.12.0" end ================================================ FILE: components/annoyance/app/models/annoyance/levels.rb ================================================ module Annoyance module Levels def self.levels [ "Huh?", "What?", "Dude!", "Hello!?", "Somebody home?", "Hey, careful with you're typing!", "Come on, this is nonsense!", "I have almost had enough!", "Really?", %q{Hairdo} ] end end end ================================================ FILE: components/annoyance/app/models/annoyance/meter.rb ================================================ module Annoyance class Meter attr_accessor :limit def initialize(limit) raise ArgumentError unless limit.is_a? Integer @limit = limit end def annoyance_level(repetition_count) raise ArgumentError unless limit.is_a? Integer return "" if repetition_count <= 0 repetition_count -= 1 index = repetition_count * Annoyance::Levels.levels.count/limit.to_f index_to_access = [index, Annoyance::Levels.levels.count - 1].min annoyance_level = Annoyance::Levels.levels[index_to_access] annoyance_level + what_to_duplicate(repetition_count, annoyance_level) * emphasis(repetition_count, index) end def annoyance_adjusted(text, repetition_count) if repetition_count < limit text + annoyance_level(repetition_count) else annoyance_level(repetition_count) end end private def emphasis(repetition_count, index) if repetition_count < limit if index - index.to_i != 0 (1/(index - index.to_i)).ceil - 1 else 0 end else repetition_count - limit + 1 end end def what_to_duplicate(repetition_count, annoyance_level) repetition_count < limit ? annoyance_level[-1] : annoyance_level end end end ================================================ FILE: components/annoyance/lib/annoyance/engine.rb ================================================ module Annoyance class Engine < ::Rails::Engine end end ================================================ FILE: components/annoyance/lib/annoyance/version.rb ================================================ module Annoyance VERSION = "0.0.1" end ================================================ FILE: components/annoyance/lib/annoyance.rb ================================================ if defined?(Rails) require 'annoyance/engine' else require_relative '../app/models/annoyance/levels' require_relative '../app/models/annoyance/meter' end module Annoyance end ================================================ FILE: components/annoyance/spec/annoyance/levels_spec.rb ================================================ require File.expand_path("../../../app/models/annoyance/levels", __FILE__) module Annoyance describe Annoyance do describe ".levels" do it "should be an array of strings" do Annoyance::Levels.levels.should be_an Array Annoyance::Levels.levels.select {|level| level.is_a? String }.count.should == Annoyance::Levels.levels.count end end end end ================================================ FILE: components/annoyance/spec/annoyance/meter_spec.rb ================================================ require File.expand_path("../../../app/models/annoyance/meter", __FILE__) module Annoyance describe Annoyance::Meter do it "should be calibrated on initialize" do meter = Annoyance::Meter.new(10) meter.limit.should == 10 end it "should raise if anything but an Integer is given" do expect { meter = Annoyance::Meter.new(:a) }.to raise_exception ArgumentError end describe "#annoyance_level" do before do Annoyance::Levels.stub(:levels).and_return( [ "level 1!", "level 2!", "level 3!", "level 4!", ] ) end it "should raise if anything but an Integer is given" do expect { meter = Annoyance::Meter.new(5).annoyance_level("a") }.to raise_exception ArgumentError end it "should return the description of the appropriate level of annoyance" do meter = Annoyance::Meter.new(4) meter.annoyance_level(1).should == "level 1!" meter.annoyance_level(2).should == "level 2!" meter.annoyance_level(3).should == "level 3!" meter.annoyance_level(4).should == "level 4!" end it "should handle impossible user input gracefully" do meter = Annoyance::Meter.new(3) meter.annoyance_level(-1).should == "" end it "should return empty string for count 0" do meter = Annoyance::Meter.new(99) meter.annoyance_level(0).should == "" meter = Annoyance::Meter.new(15) meter.annoyance_level(0).should == "" end it "should extrapolate from the last appropriate level of annoyance by duplicating the last character" do meter = Annoyance::Meter.new(8) meter.annoyance_level(1).should == "level 1!" meter.annoyance_level(2).should == "level 1!!" meter.annoyance_level(3).should == "level 2!" meter.annoyance_level(4).should == "level 2!!" meter.annoyance_level(5).should == "level 3!" meter.annoyance_level(6).should == "level 3!!" meter.annoyance_level(7).should == "level 4!" meter.annoyance_level(8).should == "level 4!!" end it "should extrapolate the last possible input by duplicating the whole result" do meter = Annoyance::Meter.new(4) meter.annoyance_level(5).should == "level 4!level 4!" meter.annoyance_level(6).should == "level 4!level 4!level 4!" end end describe "#annoyance_adjusted" do before do Annoyance::Levels.stub(:levels).and_return( [ "level 1!", "level 2!" ] ) end context "when this limit is not yet reached" do it "should annoyance adjust a given text by duplicating the last character" do meter = Annoyance::Meter.new(2) meter.annoyance_adjusted("text.", 1).should == "text.level 1!" end end context "when this limit is reached" do it "should annoyance adjust a given text by replacing the text with duplicated annoyance messages" do meter = Annoyance::Meter.new(2) meter.annoyance_adjusted("text.", 4).should == "level 2!level 2!level 2!" end end end end end ================================================ FILE: components/annoyance/spec/spec_helper.rb ================================================ #needed for newer versions of rspec. ================================================ FILE: components/annoyance/test.sh ================================================ #!/bin/bash exit_code=0 echo "*** Running annoyance gem specs" bundle install --jobs=3 --retry=3 | grep Installing bundle exec rspec spec exit_code+=$? exit $exit_code ================================================ FILE: components/email_signup/.gitignore ================================================ .bundle/ log/*.log pkg/ spec/dummy/db/*.sqlite3 spec/dummy/log/*.log spec/dummy/tmp/ spec/dummy/.sass-cache ================================================ FILE: components/email_signup/.rspec ================================================ --color ================================================ FILE: components/email_signup/.ruby-gemset ================================================ tnbtes ================================================ FILE: components/email_signup/.ruby-version ================================================ 2.1.0 ================================================ FILE: components/email_signup/Gemfile ================================================ source "https://rubygems.org" gemspec ================================================ FILE: components/email_signup/MIT-LICENSE ================================================ Copyright 2013 YOURNAME Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: components/email_signup/README.rdoc ================================================ = EmailSignup This project rocks and uses MIT-LICENSE. ================================================ FILE: components/email_signup/Rakefile ================================================ #!/usr/bin/env rake begin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end begin require 'rdoc/task' rescue LoadError require 'rdoc/rdoc' require 'rake/rdoctask' RDoc::Task = Rake::RDocTask end RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'EmailSignup' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks ================================================ FILE: components/email_signup/app/models/email_signup/entry.rb ================================================ module EmailSignup class Entry < ActiveRecord::Base # attr_accessible :email, :tries validates :email, presence: true, uniqueness: true end end ================================================ FILE: components/email_signup/app/models/email_signup/entry_manager.rb ================================================ module EmailSignup class EntryManager def create(email) return if find_by_email(email) EmailSignup::Entry.create email: email end def find_by_email(email) EmailSignup::Entry.find_by_email email end end end ================================================ FILE: components/email_signup/config/routes.rb ================================================ EmailSignup::Engine.routes.draw do end ================================================ FILE: components/email_signup/db/migrate/20130331124429_create_news_signup_entry.rb ================================================ class CreateNewsSignupEntry < ActiveRecord::Migration def change create_table "news_signup_entries", force: true do |t| t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "tries", default: 0 end end end ================================================ FILE: components/email_signup/db/migrate/20130331134505_rename_news_signup_etnries_to_email_signup_entries.rb ================================================ class RenameNewsSignupEtnriesToEmailSignupEntries < ActiveRecord::Migration def change rename_table :news_signup_entries, :email_signup_entries end end ================================================ FILE: components/email_signup/db/migrate/20130403220851_remove_tries_from_email_signup_entry.rb ================================================ class RemoveTriesFromEmailSignupEntry < ActiveRecord::Migration def change remove_column :email_signup_entries, :tries end end ================================================ FILE: components/email_signup/email_signup.gemspec ================================================ $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "email_signup/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "email_signup" s.version = EmailSignup::VERSION s.authors = ["Stephan Hagemann"] s.email = ["stephan.hagemann@gmail.com"] s.summary = "The engine that is doing signup" s.description = "The engine that is doing signup" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.add_dependency "rails", "4.1.8" s.add_development_dependency "rspec-rails", "3.1.0" s.add_development_dependency "shoulda-matchers", "2.7.0" s.add_development_dependency "sqlite3", "1.3.9" end ================================================ FILE: components/email_signup/lib/email_signup/engine.rb ================================================ module EmailSignup class Engine < ::Rails::Engine isolate_namespace EmailSignup initializer :append_migrations do |app| unless app.root.to_s.match root.to_s + File::SEPARATOR config.paths["db/migrate"].expanded.each do |path| app.config.paths["db/migrate"] << path end end end end end ================================================ FILE: components/email_signup/lib/email_signup/version.rb ================================================ module EmailSignup VERSION = "0.0.1" end ================================================ FILE: components/email_signup/lib/email_signup.rb ================================================ require "email_signup/engine" module EmailSignup end ================================================ FILE: components/email_signup/lib/tasks/news_signup_tasks.rake ================================================ # desc "Explaining what the task does" # task :email_signup do # # Task goes here # end ================================================ FILE: components/email_signup/script/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. ENGINE_ROOT = File.expand_path('../..', __FILE__) ENGINE_PATH = File.expand_path('../../lib/email_signup/engine', __FILE__) require 'rails/all' require 'rails/engine/commands' ================================================ FILE: components/email_signup/spec/dummy/README.rdoc ================================================ == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, create a new Rails application: rails new myapp (where myapp is the application name) 2. Change directory to myapp and start the web server: cd myapp; rails server (run with --help for options) 3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding Ruby on Rails!" 4. Follow the guidelines to start developing your application. You can find the following resources handy: * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or WEBrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, and then, resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use sudo gem install ruby-debug. Example: class WeblogController < ActionController::Base def index @posts = Post.all debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#nil, "body"=>nil, "id"=>"1"}>, #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you can enter "cont". == Console The console is a Ruby shell, which allows you to interact with your application's domain model. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. To start the console, run rails console from the application directory. Options: * Passing the -s, --sandbox argument will rollback any modifications made to the database. * Passing an environment name as an argument will load the corresponding environment. Example: rails console production. To reload your controllers and models after launching the console run reload! More information about irb can be found at: link:http://www.rubycentral.org/pickaxe/irb.html == dbconsole You can go to the command line of your database directly through rails dbconsole. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like rails dbconsole production. Currently works for MySQL, PostgreSQL and SQLite 3. == Description of Contents The default directory structure of a generated Ruby on Rails application: |-- app | |-- assets | | |-- images | | |-- javascripts | | `-- stylesheets | |-- controllers | |-- helpers | |-- mailers | |-- models | `-- views | `-- layouts |-- config | |-- environments | |-- initializers | `-- locales |-- db |-- doc |-- lib | |-- assets | `-- tasks |-- log |-- public |-- script |-- test | |-- fixtures | |-- functional | |-- integration | |-- performance | `-- unit |-- tmp | `-- cache | `-- assets `-- vendor |-- assets | |-- javascripts | `-- stylesheets `-- plugins app Holds all the code that's specific to this particular application. app/assets Contains subdirectories for images, stylesheets, and JavaScript files. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Models descend from ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the layout :default and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using rake doc:app lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the rails generate command, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path. ================================================ FILE: components/email_signup/spec/dummy/Rakefile ================================================ #!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Dummy::Application.load_tasks ================================================ FILE: components/email_signup/spec/dummy/app/assets/javascripts/application.js ================================================ // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree . ================================================ FILE: components/email_signup/spec/dummy/app/assets/stylesheets/application.css ================================================ /* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require_self *= require_tree . */ ================================================ FILE: components/email_signup/spec/dummy/app/controllers/application_controller.rb ================================================ class ApplicationController < ActionController::Base protect_from_forgery end ================================================ FILE: components/email_signup/spec/dummy/app/helpers/application_helper.rb ================================================ module ApplicationHelper end ================================================ FILE: components/email_signup/spec/dummy/app/mailers/.gitkeep ================================================ ================================================ FILE: components/email_signup/spec/dummy/app/models/.gitkeep ================================================ ================================================ FILE: components/email_signup/spec/dummy/app/views/layouts/application.html.erb ================================================ Dummy <%= stylesheet_link_tag "application", :media => "all" %> <%= javascript_include_tag "application" %> <%= csrf_meta_tags %> <%= yield %> ================================================ FILE: components/email_signup/spec/dummy/config/application.rb ================================================ require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" # require "active_resource/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" Bundler.require(*Rails.groups) require "email_signup" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' config.secret_key_base = "some super secret" end end ================================================ FILE: components/email_signup/spec/dummy/config/boot.rb ================================================ require 'rubygems' gemfile = File.expand_path('../../../../Gemfile', __FILE__) if File.exist?(gemfile) ENV['BUNDLE_GEMFILE'] = gemfile require 'bundler' Bundler.setup end $:.unshift File.expand_path('../../../../lib', __FILE__) ================================================ FILE: components/email_signup/spec/dummy/config/database.yml ================================================ development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 ================================================ FILE: components/email_signup/spec/dummy/config/environment.rb ================================================ # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Dummy::Application.initialize! ================================================ FILE: components/email_signup/spec/dummy/config/environments/development.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true config.eager_load = false end ================================================ FILE: components/email_signup/spec/dummy/config/environments/production.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify config.eager_load = true end ================================================ FILE: components/email_signup/spec/dummy/config/environments/test.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr config.active_support.deprecation = :stderr config.eager_load = false end ================================================ FILE: components/email_signup/spec/dummy/config/initializers/backtrace_silencers.rb ================================================ # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers! ================================================ FILE: components/email_signup/spec/dummy/config/initializers/inflections.rb ================================================ # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections do |inflect| # inflect.acronym 'RESTful' # end ================================================ FILE: components/email_signup/spec/dummy/config/initializers/mime_types.rb ================================================ # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone ================================================ FILE: components/email_signup/spec/dummy/config/initializers/secret_token.rb ================================================ # Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Dummy::Application.config.secret_token = 'b0423e3c871d076e94ed32c71a31a7ea3885fe8eb7910d0013f0213f3f30cd84395366f1d0bc5c995ce3d77a1cb4e6d16306380b4a95e1216e9b4ea66b8fb76d' ================================================ FILE: components/email_signup/spec/dummy/config/initializers/session_store.rb ================================================ # Be sure to restart your server when you modify this file. Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Dummy::Application.config.session_store :active_record_store ================================================ FILE: components/email_signup/spec/dummy/config/initializers/wrap_parameters.rb ================================================ # Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end ================================================ FILE: components/email_signup/spec/dummy/config/locales/en.yml ================================================ # Sample localization file for English. Add more files in this directory for other locales. # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. en: hello: "Hello world" ================================================ FILE: components/email_signup/spec/dummy/config/routes.rb ================================================ Rails.application.routes.draw do mount EmailSignup::Engine => "/email_signup" end ================================================ FILE: components/email_signup/spec/dummy/config.ru ================================================ # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run Dummy::Application ================================================ FILE: components/email_signup/spec/dummy/db/schema.rb ================================================ # encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20130403220851) do create_table "email_signup_entries", force: true do |t| t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false end end ================================================ FILE: components/email_signup/spec/dummy/lib/assets/.gitkeep ================================================ ================================================ FILE: components/email_signup/spec/dummy/log/.gitkeep ================================================ ================================================ FILE: components/email_signup/spec/dummy/public/404.html ================================================ The page you were looking for doesn't exist (404)

The page you were looking for doesn't exist.

You may have mistyped the address or the page may have moved.

================================================ FILE: components/email_signup/spec/dummy/public/422.html ================================================ The change you wanted was rejected (422)

The change you wanted was rejected.

Maybe you tried to change something you didn't have access to.

================================================ FILE: components/email_signup/spec/dummy/public/500.html ================================================ We're sorry, but something went wrong (500)

We're sorry, but something went wrong.

================================================ FILE: components/email_signup/spec/dummy/script/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands' ================================================ FILE: components/email_signup/spec/models/email_signup/entry_manager_spec.rb ================================================ require "spec_helper" module EmailSignup describe EmailSignup::EntryManager do before do Entry.delete_all end describe "#create" do it "creates an entry" do expect { subject.create "some_email@example.com" }.to change(Entry, :count).from(0).to(1) end it "does not create an entry with the same email address twice" do subject.create "some_email@example.com" expect { subject.create("some_email@example.com").should == nil }.to_not change(Entry, :count) end end describe "#find_by_email" do before do @entry = Entry.create! email: "some_email@example.com" end it "returns an entry iff the correct email is used" do subject.find_by_email("some_email@example.com").should == @entry subject.find_by_email("some_other_email@example.com").should == nil end end end end ================================================ FILE: components/email_signup/spec/models/email_signup/entry_spec.rb ================================================ require "spec_helper" module EmailSignup describe EmailSignup::Entry do it { should validate_presence_of :email } it { should validate_uniqueness_of :email } end end ================================================ FILE: components/email_signup/spec/spec_helper.rb ================================================ # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'shoulda-matchers' Dir[EmailSignup::Engine.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" end ================================================ FILE: components/email_signup/test.sh ================================================ #!/bin/bash exit_code=0 echo "*** Running email signup engine specs" bundle install --jobs=3 --retry=3 | grep Installing bundle exec rake db:create db:migrate #don't remove this line. If only run in test our schema.rb doesn't include required engine's migrations RAILS_ENV=test bundle exec rake db:create db:migrate bundle exec rspec spec/models exit_code+=$? exit $exit_code ================================================ FILE: components/event_counter/.gitignore ================================================ .bundle/ log/*.log pkg/ spec/dummy/db/*.sqlite3 spec/dummy/log/*.log spec/dummy/tmp/ spec/dummy/.sass-cache ================================================ FILE: components/event_counter/.rspec ================================================ --color ================================================ FILE: components/event_counter/.ruby-gemset ================================================ tnbtec ================================================ FILE: components/event_counter/.ruby-version ================================================ 2.1.0 ================================================ FILE: components/event_counter/Gemfile ================================================ source "https://rubygems.org" gemspec gem "rspec-rails" gem "shoulda-matchers" gem "sqlite3" ================================================ FILE: components/event_counter/MIT-LICENSE ================================================ Copyright 2013 YOURNAME Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: components/event_counter/README.rdoc ================================================ = EventCounter This project rocks and uses MIT-LICENSE. ================================================ FILE: components/event_counter/Rakefile ================================================ #!/usr/bin/env rake begin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end begin require 'rdoc/task' rescue LoadError require 'rdoc/rdoc' require 'rake/rdoctask' RDoc::Task = Rake::RDocTask end RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'EventCounter' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks ================================================ FILE: components/event_counter/app/models/event_counter/logger.rb ================================================ module EventCounter class Logger def log(object_identifier, event_identifier) counter = Count.where(object_identifier: object_identifier, event_identifier: event_identifier).try :first if counter.present? counter.update_attribute(:count, counter.count + 1) else counter = Count.create do |count| count.object_identifier = object_identifier count.event_identifier = event_identifier count.count = 1 end end counter.count end private class Count < ActiveRecord::Base end end end ================================================ FILE: components/event_counter/config/routes.rb ================================================ EventCounter::Engine.routes.draw do end ================================================ FILE: components/event_counter/db/migrate/20130403021547_create_event_counter_count.rb ================================================ class CreateEventCounterCount < ActiveRecord::Migration def change create_table :event_counter_counts do |t| t.string "object_identifier" t.string "event_identifier" t.integer "count", default: 0 end end end ================================================ FILE: components/event_counter/event_counter.gemspec ================================================ $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "event_counter/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "event_counter" s.version = EventCounter::VERSION s.authors = ["Stephan Hagemann"] s.email = ["stephan@pivotallabs.com"] s.homepage = "https://github.com/shageman/event_counter" s.summary = "Rails engine to count the occurences of events on objects." s.description = "This engine is part of a rails-architcture-sample app, which you can find at https://github.com/shageman/the_next_big_thing" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.add_dependency "rails", "4.1.8" s.add_development_dependency "rspec-rails", "3.1.0" s.add_development_dependency "shoulda-matchers", "1.4.2" s.add_development_dependency "sqlite3", "1.3.7" end ================================================ FILE: components/event_counter/lib/event_counter/engine.rb ================================================ module EventCounter class Engine < ::Rails::Engine isolate_namespace EventCounter initializer :append_migrations do |app| unless app.root.to_s.match root.to_s + File::SEPARATOR config.paths["db/migrate"].expanded.each do |path| app.config.paths["db/migrate"] << path end end end end end ================================================ FILE: components/event_counter/lib/event_counter/test_helper.rb ================================================ require_relative "../../spec/support/test_helper" ================================================ FILE: components/event_counter/lib/event_counter/version.rb ================================================ module EventCounter VERSION = "0.0.3" end ================================================ FILE: components/event_counter/lib/event_counter.rb ================================================ require "event_counter/engine" module EventCounter end ================================================ FILE: components/event_counter/lib/tasks/event_counter_tasks.rake ================================================ # desc "Explaining what the task does" # task :event_counter do # # Task goes here # end ================================================ FILE: components/event_counter/script/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. ENGINE_ROOT = File.expand_path('../..', __FILE__) ENGINE_PATH = File.expand_path('../../lib/event_counter/engine', __FILE__) require 'rails/all' require 'rails/engine/commands' ================================================ FILE: components/event_counter/spec/dummy/README.rdoc ================================================ == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, create a new Rails application: rails new myapp (where myapp is the application name) 2. Change directory to myapp and start the web server: cd myapp; rails server (run with --help for options) 3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding Ruby on Rails!" 4. Follow the guidelines to start developing your application. You can find the following resources handy: * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or WEBrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, and then, resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use sudo gem install ruby-debug. Example: class WeblogController < ActionController::Base def index @posts = Post.all debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#nil, "body"=>nil, "id"=>"1"}>, #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you can enter "cont". == Console The console is a Ruby shell, which allows you to interact with your application's domain model. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. To start the console, run rails console from the application directory. Options: * Passing the -s, --sandbox argument will rollback any modifications made to the database. * Passing an environment name as an argument will load the corresponding environment. Example: rails console production. To reload your controllers and models after launching the console run reload! More information about irb can be found at: link:http://www.rubycentral.org/pickaxe/irb.html == dbconsole You can go to the command line of your database directly through rails dbconsole. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like rails dbconsole production. Currently works for MySQL, PostgreSQL and SQLite 3. == Description of Contents The default directory structure of a generated Ruby on Rails application: |-- app | |-- assets | | |-- images | | |-- javascripts | | `-- stylesheets | |-- controllers | |-- helpers | |-- mailers | |-- models | `-- views | `-- layouts |-- config | |-- environments | |-- initializers | `-- locales |-- db |-- doc |-- lib | |-- assets | `-- tasks |-- log |-- public |-- script |-- test | |-- fixtures | |-- functional | |-- integration | |-- performance | `-- unit |-- tmp | `-- cache | `-- assets `-- vendor |-- assets | |-- javascripts | `-- stylesheets `-- plugins app Holds all the code that's specific to this particular application. app/assets Contains subdirectories for images, stylesheets, and JavaScript files. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Models descend from ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the layout :default and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using rake doc:app lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the rails generate command, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path. ================================================ FILE: components/event_counter/spec/dummy/Rakefile ================================================ #!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Dummy::Application.load_tasks ================================================ FILE: components/event_counter/spec/dummy/app/assets/javascripts/application.js ================================================ // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree . ================================================ FILE: components/event_counter/spec/dummy/app/assets/stylesheets/application.css ================================================ /* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require_self *= require_tree . */ ================================================ FILE: components/event_counter/spec/dummy/app/controllers/application_controller.rb ================================================ class ApplicationController < ActionController::Base protect_from_forgery end ================================================ FILE: components/event_counter/spec/dummy/app/helpers/application_helper.rb ================================================ module ApplicationHelper end ================================================ FILE: components/event_counter/spec/dummy/app/mailers/.gitkeep ================================================ ================================================ FILE: components/event_counter/spec/dummy/app/models/.gitkeep ================================================ ================================================ FILE: components/event_counter/spec/dummy/app/views/layouts/application.html.erb ================================================ Dummy <%= stylesheet_link_tag "application", :media => "all" %> <%= javascript_include_tag "application" %> <%= csrf_meta_tags %> <%= yield %> ================================================ FILE: components/event_counter/spec/dummy/config/application.rb ================================================ require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" # require "active_resource/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" Bundler.require(*Rails.groups) require "event_counter" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' end end ================================================ FILE: components/event_counter/spec/dummy/config/boot.rb ================================================ require 'rubygems' gemfile = File.expand_path('../../../../Gemfile', __FILE__) if File.exist?(gemfile) ENV['BUNDLE_GEMFILE'] = gemfile require 'bundler' Bundler.setup end $:.unshift File.expand_path('../../../../lib', __FILE__) ================================================ FILE: components/event_counter/spec/dummy/config/database.yml ================================================ development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 ================================================ FILE: components/event_counter/spec/dummy/config/environment.rb ================================================ # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Dummy::Application.initialize! ================================================ FILE: components/event_counter/spec/dummy/config/environments/development.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true config.eager_load = false end ================================================ FILE: components/event_counter/spec/dummy/config/environments/production.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 config.eager_load = true end ================================================ FILE: components/event_counter/spec/dummy/config/environments/test.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr config.active_support.deprecation = :stderr config.eager_load = false end ================================================ FILE: components/event_counter/spec/dummy/config/initializers/backtrace_silencers.rb ================================================ # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers! ================================================ FILE: components/event_counter/spec/dummy/config/initializers/inflections.rb ================================================ # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections do |inflect| # inflect.acronym 'RESTful' # end ================================================ FILE: components/event_counter/spec/dummy/config/initializers/mime_types.rb ================================================ # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone ================================================ FILE: components/event_counter/spec/dummy/config/initializers/secret_token.rb ================================================ # Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Dummy::Application.config.secret_token = '99d74f03672b06736bb127b8d46ea37b12376b45784c496263c0cfe4961387f398798a00e033b5f0de0ebe63dba51aaaa952f070fb72a7420c472a7ed88feea7' ================================================ FILE: components/event_counter/spec/dummy/config/initializers/session_store.rb ================================================ # Be sure to restart your server when you modify this file. Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Dummy::Application.config.session_store :active_record_store ================================================ FILE: components/event_counter/spec/dummy/config/initializers/wrap_parameters.rb ================================================ # Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end ================================================ FILE: components/event_counter/spec/dummy/config/locales/en.yml ================================================ # Sample localization file for English. Add more files in this directory for other locales. # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. en: hello: "Hello world" ================================================ FILE: components/event_counter/spec/dummy/config/routes.rb ================================================ Rails.application.routes.draw do mount EventCounter::Engine => "/event_counter" end ================================================ FILE: components/event_counter/spec/dummy/config.ru ================================================ # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run Dummy::Application ================================================ FILE: components/event_counter/spec/dummy/db/schema.rb ================================================ # encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20130403021547) do create_table "event_counter_counts", force: true do |t| t.string "object_identifier" t.string "event_identifier" t.integer "count", default: 0 end end ================================================ FILE: components/event_counter/spec/dummy/lib/assets/.gitkeep ================================================ ================================================ FILE: components/event_counter/spec/dummy/log/.gitkeep ================================================ ================================================ FILE: components/event_counter/spec/dummy/public/404.html ================================================ The page you were looking for doesn't exist (404)

The page you were looking for doesn't exist.

You may have mistyped the address or the page may have moved.

================================================ FILE: components/event_counter/spec/dummy/public/422.html ================================================ The change you wanted was rejected (422)

The change you wanted was rejected.

Maybe you tried to change something you didn't have access to.

================================================ FILE: components/event_counter/spec/dummy/public/500.html ================================================ We're sorry, but something went wrong (500)

We're sorry, but something went wrong.

================================================ FILE: components/event_counter/spec/dummy/script/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands' ================================================ FILE: components/event_counter/spec/models/logger_spec.rb ================================================ require "spec_helper" module EventCounter describe EventCounter::Logger do describe "#log" do it "returns the new logged count" do subject.log("some_object", "some_event").should == 1 subject.log("some_object", "some_event").should == 2 subject.log("some_object", "some_event").should == 3 subject.log("some_object", "some_other_event").should == 1 subject.log("some_other_object", "some_event").should == 1 end end end end ================================================ FILE: components/event_counter/spec/spec_helper.rb ================================================ # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'shoulda-matchers' Dir[EventCounter::Engine.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" end ================================================ FILE: components/event_counter/spec/support/test_helper.rb ================================================ module EventCounter module TestHelper def self.new_logger(object_identifier = nil, event_identifier = nil, count = nil) logger = EventCounter::Logger.new if object_identifier && event_identifier && count count.times do logger.log object_identifier, event_identifier end end logger end end end ================================================ FILE: components/event_counter/test.sh ================================================ #!/bin/bash exit_code=0 echo "*** Running event counter specs" bundle install --jobs=3 --retry=3 | grep Installing bundle exec rake db:create db:migrate #don't remove this line. If only run in test our schema.rb doesn't include required engine's migrations RAILS_ENV=test bundle exec rake db:create db:migrate bundle exec rspec spec/models exit_code+=$? exit $exit_code ================================================ FILE: components/teaser/.gitignore ================================================ .bundle/ log/*.log pkg/ spec/dummy/db/*.sqlite3 spec/dummy/log/*.log spec/dummy/tmp/ spec/dummy/.sass-cache ================================================ FILE: components/teaser/.rspec ================================================ --color ================================================ FILE: components/teaser/.ruby-gemset ================================================ tnbtt ================================================ FILE: components/teaser/.ruby-version ================================================ 2.1.0 ================================================ FILE: components/teaser/Gemfile ================================================ source "https://rubygems.org" gemspec gem 'jasmine-core', github: 'pivotal/jasmine' gem 'jasmine', github: 'pivotal/jasmine-gem' path '../' do gem "annoyance" gem "email_signup" gem "event_counter" end ================================================ FILE: components/teaser/MIT-LICENSE ================================================ Copyright 2012 YOURNAME Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: components/teaser/README.rdoc ================================================ = Teaser This project rocks and uses MIT-LICENSE. ================================================ FILE: components/teaser/Rakefile ================================================ #!/usr/bin/env rake begin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end begin require 'rdoc/task' rescue LoadError require 'rdoc/rdoc' require 'rake/rdoctask' RDoc::Task = Rake::RDocTask end RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'Teaser' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__) load 'rails/tasks/engine.rake' Bundler::GemHelper.install_tasks require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:rspec) do |spec| spec.pattern = 'spec/**/*_spec.rb' end task :default => :rspec ================================================ FILE: components/teaser/app/assets/images/teaser/.gitkeep ================================================ ================================================ FILE: components/teaser/app/assets/javascripts/teaser/application.js ================================================ // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require ./teaser //= require_tree . //= require_self (new Teaser.SignUp).initialize('#signup', '#results', window.createTeaserUrl); ================================================ FILE: components/teaser/app/assets/javascripts/teaser/signUp.js ================================================ Teaser.SignUp = function () { } Teaser.SignUp.prototype.initialize = function (inputSelector, resultSelector, signUpEndpoint) { this.signUpEndpoint = signUpEndpoint; this.$inputElement = $(inputSelector); this.$resultElement = $(resultSelector); this.$inputElement.on("keydown", $.proxy(this.signUpIfSubmitted, this)); } Teaser.SignUp.prototype.signUp = function () { var that = this; $.post(this.signUpEndpoint, { new_sign_up_entry:this.$inputElement.val() }, function (data) { }) .success(function (result) { $.proxy(that.handleSubmissionResult("success", result), that) }) .error(function (result) { $.proxy(that.handleSubmissionResult("error", result), that) }); } Teaser.SignUp.prototype.signUpIfSubmitted = function (e) { var key = (e.keyCode ? e.keyCode : e.which); if (key == 13) { e.preventDefault(); $.proxy(this.signUp(), this); } } Teaser.SignUp.prototype.handleSubmissionResult = function (result, data) { var responseText = data.responseText || data; this.$resultElement.prepend("

" + responseText + "

"); } ================================================ FILE: components/teaser/app/assets/javascripts/teaser/teaser.js ================================================ Teaser = {} ================================================ FILE: components/teaser/app/assets/stylesheets/teaser/application.css ================================================ /* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require_self *= require_tree . */ ================================================ FILE: components/teaser/app/assets/stylesheets/teaser/teaser.css.scss ================================================ /* * Colors from http://design-seeds.com/index.php/home/entry/a-door-green1 * * Thanks to design seeds! */ $lightgreen: #e4e8ae; $browngreen: #786f27; $gray: #b5acad; $darkgray: #424343; $midgreen: #cfcb65; $darkgreen: #758559; /* * You are allowed to do whatever you want with this layout. Though I would be pleased if you placed a link on your site to csseasy.com or to profit42.com (best "blog about hacking" ever). Donations are also welcome: paypal@profit42.com (or follow the donation button on csseasy.com) * * Thanks to css easy! */ * { font-family: 'Lucida Sans Unicode'; } body { background-color: $midgreen; font-size: 16px; margin: 0; padding: 0; } #header { background-color: $browngreen; height: 90px; padding: 50px; font-size: 80px; text-align: center; color: #fff; text-shadow: black 0.05em 0.05em 0.05em; } #top { width: 100%; background-color: $midgreen; height: 50px; } #center { background-color: $lightgreen; min-height: 600px; /* for modern browsers */ height: auto !important; /* for modern browsers */ height: 600px; /* for IE5.x and IE6 */ text-align: center; color: #fff; } #footer { clear: both; background-color: $browngreen; height: 200px; } #content { font-size: 28px; padding: 80px 0px; text-align: center; color: $darkgray; p { line-height: 28px; } input { background-color: white; border: 1px solid $gray; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; -moz-transition: border linear 0.2s, box-shadow linear 0.2s; -o-transition: border linear 0.2s, box-shadow linear 0.2s; transition: border linear 0.2s, box-shadow linear 0.2s; display: inline-block; height: 20px; width: 200px; padding: 4px 6px; margin-top: 20px; margin-bottom: 9px; font-size: 14px; line-height: 20px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } } ================================================ FILE: components/teaser/app/controllers/teaser/application_controller.rb ================================================ module Teaser class ApplicationController < ActionController::Base end end ================================================ FILE: components/teaser/app/controllers/teaser/tease_controller.rb ================================================ module Teaser class TeaseController < Teaser::ApplicationController before_filter :inject_dependencies, only: [:create] def new end def create email = params[:new_sign_up_entry].presence render text: "Hey! Please call this right... I need a new signUp entry!", status: 400 and return unless email if similar_exisiting_entry = @entry_manager.find_by_email(email) tries = @event_counter.log("email_signup_entry_#{similar_exisiting_entry.id}", "signup") render( text: @annoyance_meter.annoyance_adjusted("Hm... Did you already sign up?", tries), status: 400) and return elsif @entry_manager.create(email) render text: "Thanks for signing up!", status: 200 else render text: "Hm... something went seriously wrong.", status: 500 end end private def inject_dependencies @entry_manager = EmailSignup::EntryManager.new @annoyance_meter = Annoyance::Meter.new(10) @event_counter = EventCounter::Logger.new end end end ================================================ FILE: components/teaser/app/views/layouts/teaser/application.html.erb ================================================ Teaser <%= stylesheet_link_tag "teaser/application", :media => "all" %> <%= csrf_meta_tags %>
<%= content_for :top %>
Fork me on GitHub
<%= yield %>
<%= javascript_include_tag "teaser/application" %> ================================================ FILE: components/teaser/app/views/teaser/tease/new.html.haml ================================================ -content_for :header do The Next Big Thing %p Find nothing out about it right here! %p Also: sign up to receive our updates %form %input#signup #results :javascript window.createTeaserUrl = "#{tease_index_url}"; ================================================ FILE: components/teaser/config/routes.rb ================================================ Teaser::Engine.routes.draw do resources "tease", only: [:new, :create] root :to => 'tease#new' end ================================================ FILE: components/teaser/db/migrate/20120915205848_create_entry.rb ================================================ class CreateEntry < ActiveRecord::Migration def change create_table :teaser_entries do |t| t.string :email t.timestamps end end end ================================================ FILE: components/teaser/db/migrate/20120917081547_add_tries_to_teaser_entries.rb ================================================ class AddTriesToTeaserEntries < ActiveRecord::Migration def change add_column :teaser_entries, :tries, :integer, default: 0 end end ================================================ FILE: components/teaser/db/migrate/20130403011500_remove_entry.rb ================================================ class RemoveEntry < ActiveRecord::Migration def change drop_table :teaser_entries end end ================================================ FILE: components/teaser/lib/monkey_patches/engine.rb ================================================ module Rails class Engine < Railtie def load_seed seed_files = paths["db/seeds"] seed_files.each do |seed_file| load(seed_file) end end end end ================================================ FILE: components/teaser/lib/tasks/teaser_tasks.rake ================================================ # desc "Explaining what the task does" # task :teaser do # # Task goes here # end ================================================ FILE: components/teaser/lib/teaser/engine.rb ================================================ module Teaser class Engine < ::Rails::Engine isolate_namespace Teaser initializer :append_migrations do |app| unless app.root.to_s.match root.to_s + File::SEPARATOR config.paths["db/migrate"].expanded.each do |path| app.config.paths["db/migrate"] << path end end end end end ================================================ FILE: components/teaser/lib/teaser/version.rb ================================================ module Teaser VERSION = "0.0.1" end ================================================ FILE: components/teaser/lib/teaser.rb ================================================ require "teaser/engine" require "rails/all" require "haml" require "jquery-rails" require "annoyance" require "event_counter" require File.expand_path("../monkey_patches/engine.rb", __FILE__) module Teaser end ================================================ FILE: components/teaser/script/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. ENGINE_ROOT = File.expand_path('../..', __FILE__) ENGINE_PATH = File.expand_path('../../lib/teaser/engine', __FILE__) require 'rails/all' require 'rails/engine/commands' ================================================ FILE: components/teaser/spec/controllers/tease_controller_spec.rb ================================================ require "spec_helper" module Teaser describe TeaseController, type: :controller do before do controller.stub(:inject_dependencies) end describe "GET new" do it "should not fail" do expect { get :new, use_route: "teaser" }.to_not raise_exception end end describe "POST create" do it "should use the annoyance meter set to 20" do controller.unstub(:inject_dependencies) Annoyance::Meter.should_receive(:new).with(10) xhr :post, :create, use_route: "teaser" end it "should fail if no new_sign_up_entry parameter is given" do xhr :post, :create, use_route: "teaser" response.status.should == 400 response.body.should == "Hey! Please call this right... I need a new signUp entry!" xhr :post, :create, new_sign_up_entry: nil, use_route: "teaser" response.status.should == 400 response.body.should == "Hey! Please call this right... I need a new signUp entry!" end it "should fail if the given new_sign_up_entry already exists (and use the annoyance meter)" do mock_annoyance_meter = double("annoyance_meter", annoyance_adjusted: "Oh I am annoyed...") controller.instance_variable_set "@annoyance_meter", mock_annoyance_meter entry_manager = EmailSignup::EntryManager.new controller.instance_variable_set "@entry_manager", entry_manager entry = entry_manager.create "adam" event_counter = EventCounter::TestHelper.new_logger("email_signup_entry_#{entry.id}", "signup", 1) controller.instance_variable_set "@event_counter", event_counter xhr :post, :create, new_sign_up_entry: "adam", use_route: "teaser" response.status.should == 400 response.body.should == "Oh I am annoyed..." EventCounter::Logger::Count.first.count.should == 2 end it "should fail if the new entry cannot be saved" do entry_manager = double("entry_manager", create: false, find_by_email: nil) controller.instance_variable_set "@entry_manager", entry_manager xhr :post, :create, new_sign_up_entry: "something unsaveable", use_route: "teaser" response.status.should == 500 response.body.should == "Hm... something went seriously wrong." end it "should be a success if the new entry can be saved" do entry_manager = double("entry_manager", create: true, find_by_email: nil) controller.instance_variable_set "@entry_manager", entry_manager xhr :post, :create, new_sign_up_entry: "something unsaveable", use_route: "teaser" response.status.should == 200 response.body.should == "Thanks for signing up!" end end end end ================================================ FILE: components/teaser/spec/dummy/README.rdoc ================================================ == Welcome to Rails Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern. This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags. The model contains the "smart" domain objects (such as Account, Product, Person, Post) that holds all the business logic and knows how to persist themselves to a database. The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view. In Rails, the model is handled by what's called an object-relational mapping layer entitled Active Record. This layer allows you to present the data from database rows as objects and embellish these data objects with business logic methods. You can read more about Active Record in link:files/vendor/rails/activerecord/README.html. The controller and view are handled by the Action Pack, which handles both layers by its two parts: Action View and Action Controller. These two layers are bundled in a single package due to their heavy interdependence. This is unlike the relationship between the Active Record and Action Pack that is much more separate. Each of these packages can be used independently outside of Rails. You can read more about Action Pack in link:files/vendor/rails/actionpack/README.html. == Getting Started 1. At the command prompt, create a new Rails application: rails new myapp (where myapp is the application name) 2. Change directory to myapp and start the web server: cd myapp; rails server (run with --help for options) 3. Go to http://localhost:3000/ and you'll see: "Welcome aboard: You're riding Ruby on Rails!" 4. Follow the guidelines to start developing your application. You can find the following resources handy: * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ == Debugging Rails Sometimes your application goes wrong. Fortunately there are a lot of tools that will help you debug it and get it back on the rails. First area to check is the application log files. Have "tail -f" commands running on the server.log and development.log. Rails will automatically display debugging and runtime information to these files. Debugging info will also be shown in the browser on requests from 127.0.0.1. You can also log your own messages directly into the log file from your code using the Ruby logger class from inside your controllers. Example: class WeblogController < ActionController::Base def destroy @weblog = Weblog.find(params[:id]) @weblog.destroy logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") end end The result will be a message in your log file along the lines of: Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! More information on how to use the logger is at http://www.ruby-doc.org/core/ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are several books available online as well: * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) These two books will bring you up to speed on the Ruby language and also on programming in general. == Debugger Debugger support is available through the debugger command when you start your Mongrel or WEBrick server with --debugger. This means that you can break out of execution at any point in the code, investigate and change the model, and then, resume execution! You need to install ruby-debug to run the server in debugging mode. With gems, use sudo gem install ruby-debug. Example: class WeblogController < ActionController::Base def index @posts = Post.all debugger end end So the controller will accept the action, run the first line, then present you with a IRB prompt in the server window. Here you can do things like: >> @posts.inspect => "[#nil, "body"=>nil, "id"=>"1"}>, #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" >> @posts.first.title = "hello from a debugger" => "hello from a debugger" ...and even better, you can examine how your runtime objects actually work: >> f = @posts.first => #nil, "body"=>nil, "id"=>"1"}> >> f. Display all 152 possibilities? (y or n) Finally, when you're ready to resume execution, you can enter "cont". == Console The console is a Ruby shell, which allows you to interact with your application's domain model. Here you'll have all parts of the application configured, just like it is when the application is running. You can inspect domain models, change values, and save to the database. Starting the script without arguments will launch it in the development environment. To start the console, run rails console from the application directory. Options: * Passing the -s, --sandbox argument will rollback any modifications made to the database. * Passing an environment name as an argument will load the corresponding environment. Example: rails console production. To reload your controllers and models after launching the console run reload! More information about irb can be found at: link:http://www.rubycentral.org/pickaxe/irb.html == dbconsole You can go to the command line of your database directly through rails dbconsole. You would be connected to the database with the credentials defined in database.yml. Starting the script without arguments will connect you to the development database. Passing an argument will connect you to a different database, like rails dbconsole production. Currently works for MySQL, PostgreSQL and SQLite 3. == Description of Contents The default directory structure of a generated Ruby on Rails application: |-- app | |-- assets | |-- images | |-- javascripts | `-- stylesheets | |-- controllers | |-- helpers | |-- mailers | |-- models | `-- views | `-- layouts |-- config | |-- environments | |-- initializers | `-- locales |-- db |-- doc |-- lib | `-- tasks |-- log |-- public |-- script |-- test | |-- fixtures | |-- functional | |-- integration | |-- performance | `-- unit |-- tmp | |-- cache | |-- pids | |-- sessions | `-- sockets `-- vendor |-- assets `-- stylesheets `-- plugins app Holds all the code that's specific to this particular application. app/assets Contains subdirectories for images, stylesheets, and JavaScript files. app/controllers Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base. app/models Holds models that should be named like post.rb. Models descend from ActiveRecord::Base by default. app/views Holds the template files for the view that should be named like weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby syntax by default. app/views/layouts Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the layout :default and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. app/helpers Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using generators for controllers. Helpers can be used to wrap functionality for your views into methods. config Configuration files for the Rails environment, the routing map, the database, and other dependencies. db Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema. doc This directory is where your application documentation will be stored when generated using rake doc:app lib Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path. public The directory available for the web server. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server. script Helper scripts for automation and generation. test Unit and functional tests along with fixtures. When using the rails generate command, template test files will be generated for you and placed in this directory. vendor External libraries that the application depends on. Also includes the plugins subdirectory. If the app has frozen rails, those gems also go here, under vendor/rails/. This directory is in the load path. ================================================ FILE: components/teaser/spec/dummy/Rakefile ================================================ #!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Dummy::Application.load_tasks ================================================ FILE: components/teaser/spec/dummy/app/assets/javascripts/application.js ================================================ // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree . ================================================ FILE: components/teaser/spec/dummy/app/assets/stylesheets/application.css ================================================ /* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require_self *= require_tree . */ ================================================ FILE: components/teaser/spec/dummy/app/controllers/application_controller.rb ================================================ class ApplicationController < ActionController::Base protect_from_forgery end ================================================ FILE: components/teaser/spec/dummy/app/helpers/application_helper.rb ================================================ module ApplicationHelper end ================================================ FILE: components/teaser/spec/dummy/app/mailers/.gitkeep ================================================ ================================================ FILE: components/teaser/spec/dummy/app/models/.gitkeep ================================================ ================================================ FILE: components/teaser/spec/dummy/app/views/layouts/application.html.erb ================================================ Dummy <%= stylesheet_link_tag "application", :media => "all" %> <%= javascript_include_tag "application" %> <%= csrf_meta_tags %> <%= yield %> ================================================ FILE: components/teaser/spec/dummy/config/application.rb ================================================ require File.expand_path('../boot', __FILE__) require "rails/all" Bundler.require require "teaser" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' config.secret_key_base = "some super secret" end end ================================================ FILE: components/teaser/spec/dummy/config/boot.rb ================================================ require 'rubygems' gemfile = File.expand_path('../../../../Gemfile', __FILE__) if File.exist?(gemfile) ENV['BUNDLE_GEMFILE'] = gemfile require 'bundler' Bundler.setup end $:.unshift File.expand_path('../../../../lib', __FILE__) ================================================ FILE: components/teaser/spec/dummy/config/database.yml ================================================ development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 ================================================ FILE: components/teaser/spec/dummy/config/environment.rb ================================================ # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Dummy::Application.initialize! ================================================ FILE: components/teaser/spec/dummy/config/environments/development.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true config.eager_load = false end ================================================ FILE: components/teaser/spec/dummy/config/environments/production.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify config.eager_load = true end ================================================ FILE: components/teaser/spec/dummy/config/environments/test.rb ================================================ Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr config.active_support.deprecation = :stderr config.eager_load = false end ================================================ FILE: components/teaser/spec/dummy/config/initializers/backtrace_silencers.rb ================================================ # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers! ================================================ FILE: components/teaser/spec/dummy/config/initializers/inflections.rb ================================================ # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections do |inflect| # inflect.acronym 'RESTful' # end ================================================ FILE: components/teaser/spec/dummy/config/initializers/mime_types.rb ================================================ # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone ================================================ FILE: components/teaser/spec/dummy/config/initializers/secret_token.rb ================================================ # Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. Dummy::Application.config.secret_token = '38740bca001ba4e3a23cc52b7774f35821467eab796e2a0c3fb202d083b9d995d049a1788ae3091e08ad55656852e75a08f42858e7bf03b147db2e18bf4bc94e' ================================================ FILE: components/teaser/spec/dummy/config/initializers/session_store.rb ================================================ # Be sure to restart your server when you modify this file. Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Dummy::Application.config.session_store :active_record_store ================================================ FILE: components/teaser/spec/dummy/config/initializers/wrap_parameters.rb ================================================ # Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end ================================================ FILE: components/teaser/spec/dummy/config/locales/en.yml ================================================ # Sample localization file for English. Add more files in this directory for other locales. # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. en: hello: "Hello world" ================================================ FILE: components/teaser/spec/dummy/config/routes.rb ================================================ Rails.application.routes.draw do mount Teaser::Engine => "/teaser" end ================================================ FILE: components/teaser/spec/dummy/config.ru ================================================ # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run Dummy::Application ================================================ FILE: components/teaser/spec/dummy/db/schema.rb ================================================ # encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20130403220851) do create_table "email_signup_entries", force: true do |t| t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "event_counter_counts", force: true do |t| t.string "object_identifier" t.string "event_identifier" t.integer "count", default: 0 end end ================================================ FILE: components/teaser/spec/dummy/lib/assets/.gitkeep ================================================ ================================================ FILE: components/teaser/spec/dummy/log/.gitkeep ================================================ ================================================ FILE: components/teaser/spec/dummy/public/404.html ================================================ The page you were looking for doesn't exist (404)

The page you were looking for doesn't exist.

You may have mistyped the address or the page may have moved.

================================================ FILE: components/teaser/spec/dummy/public/422.html ================================================ The change you wanted was rejected (422)

The change you wanted was rejected.

Maybe you tried to change something you didn't have access to.

================================================ FILE: components/teaser/spec/dummy/public/500.html ================================================ We're sorry, but something went wrong (500)

We're sorry, but something went wrong.

================================================ FILE: components/teaser/spec/dummy/script/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands' ================================================ FILE: components/teaser/spec/dummy/teaser_test ================================================ ================================================ FILE: components/teaser/spec/features/signing_up_for_updates_spec.rb ================================================ require "request_spec_helper" feature "Signing up for tnbt updates", %q{ In order to stay informed about the next big thing As a person I want to be able to sign up to updates } do background do EmailSignup::Entry.delete_all end scenario "sign up", js: "true" do visit teaser.root_path expect { fill_in "signup", with: "stephan@pivotallabs.com" press_key_on_selector(13, "#signup") page.should have_content "Thanks for signing up!" }.to change(EmailSignup::Entry, :count).from(0).to(1) end end ================================================ FILE: components/teaser/spec/javascripts/helpers/mock-ajax.js ================================================ /* Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine BDD framework for JavaScript. http://github.com/pivotal/jasmine-ajax Jasmine Home page: http://pivotal.github.com/jasmine Copyright (c) 2008-2013 Pivotal Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function() { function extend(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; } function MockAjax(global) { var requestTracker = new RequestTracker(), stubTracker = new StubTracker(), realAjaxFunction = global.XMLHttpRequest, mockAjaxFunction = fakeRequest(requestTracker, stubTracker); this.install = function() { global.XMLHttpRequest = mockAjaxFunction; }; this.uninstall = function() { global.XMLHttpRequest = realAjaxFunction; }; this.stubRequest = function(url) { var stub = new RequestStub(url); stubTracker.addStub(stub); return stub; }; this.withMock = function(closure) { this.install(); try { closure(); } finally { this.uninstall(); } }; this.requests = requestTracker; this.stubs = stubTracker; } function StubTracker() { var stubs = []; this.addStub = function(stub) { stubs.push(stub); }; this.reset = function() { stubs = []; }; this.findStub = function(url) { for (var i = stubs.length - 1; i >= 0; i--) { var stub = stubs[i]; if (stub.url === url) { return stub; } } }; } function fakeRequest(requestTracker, stubTracker) { function FakeXMLHttpRequest() { requestTracker.track(this); } extend(FakeXMLHttpRequest.prototype, window.XMLHttpRequest); extend(FakeXMLHttpRequest.prototype, { requestHeaders: {}, open: function() { this.method = arguments[0]; this.url = arguments[1]; this.username = arguments[3]; this.password = arguments[4]; this.readyState = 1; }, setRequestHeader: function(header, value) { this.requestHeaders[header] = value; }, abort: function() { this.readyState = 0; }, readyState: 0, onload: function() { }, onreadystatechange: function(isTimeout) { }, status: null, send: function(data) { this.params = data; this.readyState = 2; var stub = stubTracker.findStub(this.url); if (stub) { this.response(stub); } }, data: function() { var data = {}; if (typeof this.params !== 'string') { return data; } var params = this.params.split('&'); for (var i = 0; i < params.length; ++i) { var kv = params[i].replace(/\+/g, ' ').split('='); var key = decodeURIComponent(kv[0]); data[key] = data[key] || []; data[key].push(decodeURIComponent(kv[1])); data[key].sort(); } return data; }, getResponseHeader: function(name) { return this.responseHeaders[name]; }, getAllResponseHeaders: function() { var responseHeaders = []; for (var i in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(i)) { responseHeaders.push(i + ': ' + this.responseHeaders[i]); } } return responseHeaders.join('\r\n'); }, responseText: null, response: function(response) { this.status = response.status; this.responseText = response.responseText || ""; this.readyState = 4; this.responseHeaders = response.responseHeaders || {"Content-type": response.contentType || "application/json" }; this.onload(); this.onreadystatechange(); }, responseTimeout: function() { this.readyState = 4; clock.tick(30000); this.onreadystatechange('timeout'); } }); return FakeXMLHttpRequest; } function RequestTracker() { var requests = []; this.track = function(request) { requests.push(request); }; this.first = function() { return requests[0]; }; this.count = function() { return requests.length; }; this.reset = function() { requests = []; }; this.mostRecent = function() { return requests[requests.length - 1]; }; this.at = function(index) { return requests[index]; }; } function RequestStub(url) { this.url = url; this.andReturn = function(options) { this.status = options.status || 200; this.contentType = options.contentType; this.responseText = options.responseText; }; } if (typeof window === "undefined" && typeof exports === "object") { exports.MockAjax = MockAjax; jasmine.Ajax = new MockAjax(exports); } else { window.MockAjax = MockAjax; jasmine.Ajax = new MockAjax(window); } }()); ================================================ FILE: components/teaser/spec/javascripts/support/jasmine.yml ================================================ # src_files # # Return an array of filepaths relative to src_dir to include before jasmine specs. # Default: [] # # EXAMPLE: # # src_files: # - lib/source1.js # - lib/source2.js # - dist/**/*.js # src_files: - assets/teaser/application.js # stylesheets # # Return an array of stylesheet filepaths relative to src_dir to include before jasmine specs. # Default: [] # # EXAMPLE: # # stylesheets: # - css/style.css # - stylesheets/*.css # stylesheets: - stylesheets/teaster/**/*.css # helpers # # Return an array of filepaths relative to spec_dir to include before jasmine specs. # Default: ["helpers/**/*.js"] # # EXAMPLE: # # helpers: # - helpers/**/*.js # helpers: - helpers/**/*.js - helpers/mock-ajax.js # spec_files # # Return an array of filepaths relative to spec_dir to include. # Default: ["**/*[sS]pec.js"] # # EXAMPLE: # # spec_files: # - **/*[sS]pec.js # spec_files: - '**/*[sS]pec.js' # src_dir # # Source directory path. Your src_files must be returned relative to this path. Will use root if left blank. # Default: project root # # EXAMPLE: # # src_dir: public # src_dir: - sources/**/*.js # spec_dir # # Spec directory path. Your spec_files must be returned relative to this path. # Default: spec/javascripts # # EXAMPLE: # # spec_dir: spec/javascripts # spec_dir: spec/javascripts ================================================ FILE: components/teaser/spec/javascripts/teaser/signup_spec.js ================================================ describe("Teaser.SignUp", function () { describe("#initialize", function () { it("should transform the given parameters into variables on the object", function () { $("#jasmine_content").html("

within p

within div
"); var signUp = new Teaser.SignUp; signUp.initialize(".input", ".result", "signUpEndpoint"); expect(signUp.signUpEndpoint).toEqual("signUpEndpoint"); expect(signUp.$inputElement.html()).toEqual("within p"); expect(signUp.$resultElement.html()).toEqual("within div"); }); it("should register signUpIfSubmitted on keydowns in the input", function () { var signUpIfSubmitted = spyOn(Teaser.SignUp.prototype, "signUpIfSubmitted"); $("#jasmine_content").html("

within p

within div
"); var signUp = new Teaser.SignUp; signUp.initialize(".input", ".result", "signUpEndpoint"); $(".input").trigger("keydown") expect(signUpIfSubmitted).toHaveBeenCalled(); }); }); describe("#signUp", function () { var handleSubmissionResult, request; var callAjax = function () { jasmine.Ajax.install(); handleSubmissionResult = spyOn(Teaser.SignUp.prototype, "handleSubmissionResult"); var signUp = new Teaser.SignUp; signUp.signUpEndpoint = "signUpEndpoint"; signUp.$inputElement = {val:function () { return "value of input" }} signUp.signUp(); request = jasmine.Ajax.requests.mostRecent(); } it("should post the value of the input element to the signUpEndpoint", function () { pending("don't yet know how to do this test with the new jasmine API") var post = spyOn($, "post").andCallThrough(); callAjax(); expect(post).toHaveBeenCalledWith("signUpEndpoint", { new_sign_up_entry:"value of input" }, jasmine.any(Function)); }); it("should call handleSubmissionResult with success if the ajax call is successful", function () { callAjax(); request.response({status:200, responseText:"{}"}); expect(handleSubmissionResult).toHaveBeenCalledWith("success", {}); }); it("should call handleSubmissionResult with error if the ajax call is unsuccessful", function () { callAjax(); request.response({status:400, responseText:""}); expect(handleSubmissionResult).toHaveBeenCalledWith("error", jasmine.any(Object)); }); }); describe("#signUpIfSubmitted", function () { var signUp, event; beforeEach(function () { signUp = new Teaser.SignUp; spyOn(signUp, "signUp"); event = jQuery.Event("keydown"); }); describe("when the key pressed is Enter", function () { beforeEach(function () { event.keyCode = 13; }); it("should prevent default", function () { spyOn(event, "preventDefault"); signUp.signUpIfSubmitted(event); expect(event.preventDefault).toHaveBeenCalled(); }); it("should call signUp", function () { signUp.signUpIfSubmitted(event); expect(signUp.signUp).toHaveBeenCalled(); }); }); describe("when the key pressed is not Enter", function () { beforeEach(function () { event.keyCode = 14; }); it("should not prevent default", function () { spyOn(event, "preventDefault"); signUp.signUpIfSubmitted(event); expect(event.preventDefault).not.toHaveBeenCalled(); }); it("should not call signUp", function () { signUp.signUpIfSubmitted(event); expect(signUp.signUp).not.toHaveBeenCalled(); }); }); }); describe("handleSubmissionResult", function () { var signUp; beforeEach(function () { $("#jasmine_content").html("
"); signUp = new Teaser.SignUp; signUp.$resultElement = $(".result"); }); it("should prepend the result's responseText to the $resultElement", function () { signUp.handleSubmissionResult("success_class", {responseText: "this was a success"}); expect(signUp.$resultElement.html()).toEqual('

this was a success

'); }); it("should prepend the result to the $resultElement (if there is no responseText)", function () { signUp.handleSubmissionResult("success_class", "this was also a success"); expect(signUp.$resultElement.html()).toEqual('

this was also a success

'); }); }); }); ================================================ FILE: components/teaser/spec/request_spec_helper.rb ================================================ ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment", __FILE__) require 'rspec/rails' require 'capybara/rspec' require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist Dir[Teaser::Engine.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.use_transactional_fixtures = false config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.include RequestSpecHelpers config.include Capybara::DSL end ================================================ FILE: components/teaser/spec/spec_helper.rb ================================================ ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment", __FILE__) require 'rspec/rails' require 'shoulda-matchers' require 'event_counter/test_helper' Dir[Teaser::Engine.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" end ================================================ FILE: components/teaser/spec/support/request_spec_helpers.rb ================================================ module RequestSpecHelpers def press_key_on_selector(key, selector) page.driver.execute_script("var e = $.Event('keydown', { keyCode: #{key} }); $('#{selector}').trigger(e);") end end ================================================ FILE: components/teaser/teaser.gemspec ================================================ $:.push File.expand_path("../lib", __FILE__) # Maintain your gem"s version: require "teaser/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "teaser" s.version = Teaser::VERSION s.authors = ["Stephan Hagemann"] s.email = ["stephan.hagemann@gmail.com"] s.summary = "Teaser gem" s.description = "Teaser gem" s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"] s.add_dependency "rails", "4.1.8" s.add_dependency "haml-rails", "0.5.3" s.add_dependency "sass-rails", "4.0.1" s.add_dependency "jquery-rails", "3.1.0" s.add_dependency "event_counter" s.add_dependency "annoyance" s.add_dependency "email_signup" s.add_development_dependency "rspec-rails", "3.1.0" s.add_development_dependency "capybara", "2.4.1" s.add_development_dependency "shoulda-matchers", "2.7.0" s.add_development_dependency "sqlite3", "1.3.9" s.add_development_dependency "poltergeist", "1.5.1" s.add_development_dependency "jasmine", "1.3.2" end ================================================ FILE: components/teaser/test.sh ================================================ #!/bin/bash exit_code=0 echo "*** Running teaser engine specs" bundle install --jobs=3 --retry=3 | grep Installing bundle exec rake db:create bundle exec rake db:migrate RAILS_ENV=test bundle exec rake db:create RAILS_ENV=test bundle exec rake db:migrate bundle exec rspec spec/controllers exit_code+=$? echo "*** Running teaser engine request specs" bundle exec rspec spec/features exit_code+=$? echo "*** Running teaser engine javascript specs" bundle exec rake app:jasmine:ci exit_code+=$? exit $exit_code ================================================ FILE: config/application.rb ================================================ require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: # require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" # require "active_resource/railtie" require "sprockets/railtie" #require "rails/test_unit/railtie" if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.require(:default, :assets, Rails.env) end module TheNextBigThing class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # Enable escaping HTML in JSON. config.active_support.escape_html_entities_in_json = true # Use SQL instead of Active Record's schema dumper when creating the database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Enforce whitelist mode for mass assignment. # This will create an empty whitelist of attributes available for mass-assignment for all models # in your app. As such, your models will need to explicitly whitelist or blacklist accessible # parameters by using an attr_accessible or attr_protected declaration. # config.active_record.whitelist_attributes = true # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' #config.assets.initialize_on_precompile = false config.secret_key_base = "some super secret" end end ================================================ FILE: config/boot.rb ================================================ require 'rubygems' # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) ================================================ FILE: config/database.yml ================================================ development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 ================================================ FILE: config/environment.rb ================================================ # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application TheNextBigThing::Application.initialize! ================================================ FILE: config/environments/development.rb ================================================ TheNextBigThing::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin config.eager_load = false end ================================================ FILE: config/environments/production.rb ================================================ TheNextBigThing::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify config.eager_load = true end ================================================ FILE: config/environments/test.rb ================================================ TheNextBigThing::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr config.active_support.deprecation = :stderr config.eager_load = false end ================================================ FILE: config/initializers/backtrace_silencers.rb ================================================ # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers! ================================================ FILE: config/initializers/inflections.rb ================================================ # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections do |inflect| # inflect.acronym 'RESTful' # end ================================================ FILE: config/initializers/mime_types.rb ================================================ # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone ================================================ FILE: config/initializers/secret_token.rb ================================================ # Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. TheNextBigThing::Application.config.secret_token = 'f0a8e268c6f152a6a8a4833925366d511d62b85fa34098ed120238540e068c9578636785b920537a10c84bc0e512a6f6e0e782e6852971cabeacf96019a85c71' ================================================ FILE: config/initializers/session_store.rb ================================================ # Be sure to restart your server when you modify this file. TheNextBigThing::Application.config.session_store :cookie_store, key: '_the_next_big_thing_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # TheNextBigThing::Application.config.session_store :active_record_store ================================================ FILE: config/initializers/wrap_parameters.rb ================================================ # Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end ================================================ FILE: config/locales/en.yml ================================================ # Sample localization file for English. Add more files in this directory for other locales. # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. en: hello: "Hello world" ================================================ FILE: config/routes.rb ================================================ TheNextBigThing::Application.routes.draw do mount Teaser::Engine => "/" end ================================================ FILE: config.ru ================================================ # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run TheNextBigThing::Application ================================================ FILE: db/schema.rb ================================================ # encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20130403220851) do create_table "email_signup_entries", force: true do |t| t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "event_counter_counts", force: true do |t| t.string "object_identifier" t.string "event_identifier" t.integer "count", default: 0 end end ================================================ FILE: db/seeds.rb ================================================ # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) ================================================ FILE: log/.gitkeep ================================================ ================================================ FILE: migrate_and_prepare_all.sh ================================================ #!/bin/bash [ -s "$HOME/.rvm/scripts/rvm" ] && . "$HOME/.rvm/scripts/rvm" echo "migrating teaser" cd engines/teaser && rake db:migrate app:db:test:prepare && cd ../.. echo "migrating wrapper rails app" rake db:migrate db:test:prepare ================================================ FILE: public/404.html ================================================ The page you were looking for doesn't exist (404)

The page you were looking for doesn't exist.

You may have mistyped the address or the page may have moved.

================================================ FILE: public/422.html ================================================ The change you wanted was rejected (422)

The change you wanted was rejected.

Maybe you tried to change something you didn't have access to.

================================================ FILE: public/500.html ================================================ We're sorry, but something went wrong (500)

We're sorry, but something went wrong.

================================================ FILE: public/robots.txt ================================================ # See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file # # To ban all spiders from the entire site uncomment the next two lines: # User-Agent: * # Disallow: / ================================================ FILE: script/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands' ================================================ FILE: spec/features/home_page_spec.rb ================================================ require "spec_helper" feature "The Next Big Thing Homepage", %q{ In order to get informed about the next big thing As a person I want to be able to read about nothing definite about it and sign up for more info } do scenario "The Homepage" do visit "/" page.should have_content("The Next Big Thing") page.should have_content("Find nothing out about it right here!") end end ================================================ FILE: spec/fixtures/.gitkeep ================================================ ================================================ FILE: spec/spec_helper.rb ================================================ ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'capybara/rspec' Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.order = "random" end ================================================ FILE: test.sh ================================================ #!/bin/bash exit_code=0 echo "*** Running container app specs" bundle install --jobs=3 --retry=3 | grep Installing bundle exec rake db:create db:migrate #don't remove this line. If only run in test our schema.rb doesn't include required engine's migrations RAILS_ENV=test bundle exec rake db:create db:migrate bundle exec rspec spec exit_code+=$? exit $exit_code ================================================ FILE: vendor/assets/javascripts/.gitkeep ================================================ ================================================ FILE: vendor/assets/stylesheets/.gitkeep ================================================ ================================================ FILE: vendor/plugins/.gitkeep ================================================