repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/controllers/sessions_controller.rb | app/controllers/sessions_controller.rb | class SessionsController < ApplicationController
##############################################################################
# We need to disable the `require_authentication` before filter that
# was added in the ApplicationController otherwise when the user
# tries to access the login form he/she will be redirected to the
# login form (an infinite loop of redirects).
skip_filter(:require_authentication)
##############################################################################
# We don't need an index method for this controller, we we'll just
# force the user to redirect to '/'.
def index
redirect_to(root_path)
end
##############################################################################
# The new method is where we can show the login form to the user.
# Rails will automatically render the app/views/sessions/new.html.erb file.
def new
end
##############################################################################
# The form in new.html.erb will post to this method.
def create
email, password = params[:user][:email], params[:user][:password]
if user = User.authenticate(email, password)
session[:user_id] = user.id
redirect_to(root_url, :notice => 'Logged in!')
else
flash.now.alert = 'Invalid email address or password'
render('new') # render new.html.erb
end
end
##############################################################################
# The last method we need is `destroy` which we'll use to log the
# current user out.
def destroy
session[:user_id] = nil
redirect_to(root_path)
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
##############################################################################
# Enable forgery protection. See http://en.wikipedia.org/wiki/CSRF
protect_from_forgery
##############################################################################
private
##############################################################################
# Return the logged in user, if there is one. This method, and all
# others defined in this file, are available to all of the other
# controllers due to inheritance.
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
##############################################################################
# Returns true if a user is logged in.
def logged_in?
!current_user.blank?
end
##############################################################################
# Export the `current_user` and `logged_in?` methods to the views.
helper_method(:current_user, :logged_in?)
##############################################################################
# This method will be used as a before filter so we can force a
# redirect if the current user hasn't logged in yet.
def require_authentication
redirect_to(login_path) unless logged_in?
end
##############################################################################
# By placing the filter here, in the ApplicationController, all
# other controllers will inherit it. That means all other
# controllers in this application require a user to be logged in, or
# they get redirected to the login form. Take a look at the
# sessions controller for information about how to disabled this
# global before filter.
before_filter(:require_authentication)
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/controllers/cars_controller.rb | app/controllers/cars_controller.rb | class CarsController < ApplicationController
##############################################################################
# The following class method tells Rails what formats we can respond
# with. This is necessary to use the `respond_with` helper later.
respond_to(:html, :xml, :json)
##############################################################################
# Load all cars for the current user. Rails automatically renders
# the app/views/cars/index.html.erb file.
def index
@cars = current_user.cars.order(:name)
respond_with(@cars)
end
##############################################################################
# Normally, if a model had enough information to display on a
# dedicated page you would do so here in the show action. Since a
# car only has a name it doesn't make much sense to show that by
# itself, so we'll just redirect to the index action.
def show
redirect_to(cars_path)
end
##############################################################################
# Using `respond_with` below will automatically render
# app/views/cars/new.html.erb if the current request wants HTML, or
# it can render XML or JSON if that's what the request calls for.
def new
@car = current_user.cars.new
respond_with(@car)
end
##############################################################################
def create
@car = current_user.cars.create(params[:car])
respond_with(@car)
end
##############################################################################
def edit
@car = current_user.cars.find(params[:id])
respond_with(@car)
end
##############################################################################
def update
@car = current_user.cars.find(params[:id])
@car.update_attributes(params[:car])
respond_with(@car)
end
##############################################################################
def destroy
@car = current_user.cars.find(params[:id])
@car.destroy
respond_with(@car)
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/models/refuel.rb | app/models/refuel.rb | class Refuel < ActiveRecord::Base
##############################################################################
attr_accessible(:refueled_at, :odometer, :gallons, :price)
##############################################################################
validates(:refueled_at, :presence => true)
validates(:odometer, :presence => true, :numericality => true)
validates(:gallons, :presence => true, :numericality => true)
validates(:price_cents, :presence => true, :numericality => true)
##############################################################################
# We're going to use the money gem to map the price_cents attribute
# to a Money object. To make the price_cents attribute
# transparently appear as a Money object through the price attribute
# we need to tell ActiveRecord how to do the conversion.
#
# After we use the `composed_of` call below we can read and write a
# Money object on the price attribute and it will automatically be
# converted to and from our integer attribute price_cents.
composed_of(:price,
:class_name => "Money",
:mapping => [%w(price_cents cents)],
:constructor => lambda {|cents| Money.new(cents || 0)},
:converter => lambda {|value| value.to_money})
##############################################################################
belongs_to(:car) # refuel.car
##############################################################################
# A scope is a way to give a name to database query so it can be
# accessed by other models, controllers, and views. You can see
# this being used in app/views/cars/index.html.erb.
scope(:most_recent, order('refueled_at DESC').limit(1))
##############################################################################
# This method is used to find a refuel that occurred just prior to
# this one. We'll use this later to calculate MPG and distance
# based on the previous refuel.
def preceding
car.refuels.where('refueled_at < ?', refueled_at).order('refueled_at DESC').first
end
##############################################################################
# Returns the refuel that happened after this one. See also:
# preceding.
def following
car.refuels.where('refueled_at > ?', refueled_at).order('refueled_at').first
end
##############################################################################
def formatted_mpg
"%.2f" % [mpg || 0.0]
end
##############################################################################
def cost_per_mile
if other = preceding
preceding.price / distance
end
end
##############################################################################
private
##############################################################################
# A private instance method to calculate and cache the mpg and
# distance fields using the refuel that happened prior to this one.
def cache_mpg_and_distance
if other = preceding
self.distance = odometer - preceding.odometer
self.mpg = distance / gallons
end
end
##############################################################################
# This callback will only be invoked when a new record is being
# saved for the first time.
before_create do
cache_mpg_and_distance if distance.blank? or mpg.blank?
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/models/car.rb | app/models/car.rb | class Car < ActiveRecord::Base
##############################################################################
attr_accessible(:name)
##############################################################################
# Validate that the name of a car is unique, but only for a single
# user. That is, a single user can't have more than one car with
# the same name, but two users can have a car with the same name.
validates(:name, :presence => true, :uniqueness => {:scope => :user_id})
##############################################################################
belongs_to(:user) # Allows you to access a user: car.user
has_many(:refuels) # Gives you an array of refuels: car.refuels
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/models/user.rb | app/models/user.rb | class User < ActiveRecord::Base
##############################################################################
# Restrict which attributes can be changed through mass-assignment
# (for example, from an HTML form). The password and
# password_confirmation attributes are created below when we call
# `has_secure_password`.
attr_accessible(:first_name, :last_name, :email,
:password, :password_confirmation)
##############################################################################
# Validate user attributes before they are allowed to be saved to
# the database. Rails 3.1 allows you to group your validations by
# attribute.
validates(:first_name, :presence => true)
validates(:last_name, :presence => true)
validates(:email, :presence => true, :format => /^.+@.+/)
##############################################################################
# Use the Rails 3.1 built-in authentication helpers. This call adds
# two additional attributes `password` and `password_confirmation`
# and also adds the necessary validation for them. If you wanted
# you could add additional validations for the password attribute
# (e.g. requiring a minimum number of characters).
has_secure_password
##############################################################################
# Tell ActiveRecord how this model relates to other models.
has_many(:cars)
##############################################################################
# Help keep email addresses in a consistent format so we can look
# them up in the database we can find them regardless of the case
# and spacing the user entered in a form.
def self.clean_email (email)
email.to_s.strip.downcase
end
##############################################################################
# Add a class method that helps us find and authenticate a user
# based on their email address. This isn't strictly necessary but
# it's advisable to keep the majority of your logic in a model or
# library file.
def self.authenticate (email, clear_text_password)
find_by_email(clean_email(email)).try(:authenticate, clear_text_password)
end
##############################################################################
private
##############################################################################
# One of the many callbacks you can define on a model. This one
# gets called before a user object is validated.
before_validation do
# Standardize the email attribute
self.email = self.class.clean_email(email)
# Why self.email? This is a parsing ambiguity in Ruby. If you
# just use `email = 'foo'` Ruby will create a local variable
# instead of calling the attribute setter method `email=`. You
# only need to use the form `self.something` when doing an
# assignment through a setter method.
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/db/seeds.rb | 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)
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/db/schema.rb | db/schema.rb | # 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 to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20111102210426) do
create_table "cars", :force => true do |t|
t.integer "user_id"
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "cars", ["user_id"], :name => "index_cars_on_user_id"
create_table "refuels", :force => true do |t|
t.integer "car_id"
t.datetime "refueled_at"
t.integer "odometer"
t.float "gallons"
t.float "mpg"
t.integer "distance"
t.integer "price_cents", :default => 0
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "refuels", ["car_id", "refueled_at"], :name => "index_refuels_on_car_id_and_refueled_at", :unique => true
add_index "refuels", ["car_id"], :name => "index_refuels_on_car_id"
create_table "users", :force => true do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/db/migrate/20111102210426_create_refuels.rb | db/migrate/20111102210426_create_refuels.rb | class CreateRefuels < ActiveRecord::Migration
##############################################################################
def change
create_table(:refuels) do |t|
t.column(:car_id, :integer)
t.column(:refueled_at, :datetime)
t.column(:odometer, :integer)
t.column(:gallons, :float)
t.column(:mpg, :float)
t.column(:distance, :integer)
t.column(:price_cents, :integer, :default => 0)
t.timestamps
end
add_index(:refuels, :car_id)
add_index(:refuels, [:car_id, :refueled_at], :unique => true)
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/db/migrate/20111102192932_create_cars.rb | db/migrate/20111102192932_create_cars.rb | class CreateCars < ActiveRecord::Migration
##############################################################################
def change
create_table(:cars) do |t|
# Create a foreign key to link to the users table. This could
# have been: t.belongs_to(:user)
t.column(:user_id, :integer)
t.column(:name, :string)
t.timestamps
end
# Add a database index for user_id since we'll most often be
# pulling cars using that column.
add_index(:cars, :user_id)
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/db/migrate/20111102182704_create_users.rb | db/migrate/20111102182704_create_users.rb | class CreateUsers < ActiveRecord::Migration
##############################################################################
# With Rails 3.1 you only need one method in your migration:
# `change`. It's an instance method and if you are reverting a
# migration its actions are reversed automatically.
#
# If you need more control you can define two instance methods: `up`
# and `down`.
def change
create_table(:users) do |t|
t.column(:first_name, :string)
t.column(:last_name, :string)
t.column(:email, :string)
t.column(:password_digest, :string)
# The following shortcut creates two columns in the database:
# `created_at` and `updated_at` which Rails automatically
# updates as necessary.
t.timestamps
end
end
##############################################################################
# Some people prefer this alternate version of create_table (which
# does the same thing):
#
# create_table(:users) do |t|
# t.string(:first_name)
# t.string(:last_name)
# t.string(:email)
# t.string(:password_digest)
# t.timestamps
# end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/factories.rb | test/factories.rb | ################################################################################
# FactoryGirl is a nice replacement for test fixtures. For more
# information please see:
#
# https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md
#
FactoryGirl.define do
##############################################################################
factory(:user) do
first_name('John')
last_name('Doe')
password('fubar')
password_confirmation('fubar')
sequence(:email) {|n| "person#{n}@example.com"}
end
##############################################################################
factory(:car) do
name('Toyota Land Cruiser')
user
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/test_helper.rb | test/test_helper.rb | ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/integration/login_flow_test.rb | test/integration/login_flow_test.rb | ################################################################################
require('test_helper')
################################################################################
class LoginFlowTest < ActionDispatch::IntegrationTest
##############################################################################
test "user can login and then log out" do
user = FactoryGirl.create(:user)
# Going to / should redirect us to login
get('/')
assert_response(:redirect)
assert_redirected_to(login_path)
# Going to /login should return the login form
get('/login')
assert_response(:success)
assert_template(:new)
# Posting to /sessions should log us in
post('/sessions', :user => {:email => user.email, :password => 'fubar'})
assert_response(:redirect)
assert_redirected_to(root_path)
# Going to / should show us our cars
get('/')
assert_response(:success)
assert_template(:index)
assert(assigns(:cars))
# Going to /logout should log us out
get('/logout')
assert_response(:redirect)
assert_redirected_to(root_path)
# Going to / should redirect us to login
get('/')
assert_response(:redirect)
assert_redirected_to(login_path)
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/performance/browsing_test.rb | test/performance/browsing_test.rb | require 'test_helper'
require 'rails/performance_test_help'
class BrowsingTest < ActionDispatch::PerformanceTest
# Refer to the documentation for all available options
# self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory]
# :output => 'tmp/performance', :formats => [:flat] }
def test_homepage
get '/'
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/unit/user_test.rb | test/unit/user_test.rb | ################################################################################
require('test_helper')
################################################################################
class UserTest < ActiveSupport::TestCase
##############################################################################
test "ensure we have authentication working correctly" do
user = User.new(:first_name => 'John', :last_name => 'Doe', :email => 'Fake@example.com')
user.password = 'fubar'
user.password_confirmation = 'not-fubar'
assert(!user.valid?)
user.password_confirmation = 'fubar'
assert(user.valid?)
assert(user.save)
found = User.where(:email => 'fake@example.com').first
assert_equal(user, found)
assert(found.authenticate('fubar'))
assert(!found.authenticate('something else'))
# Try using our class method shortcut
assert_equal(user, User.authenticate('fake@example.COM', 'fubar'))
assert(!User.authenticate('fake@example.com', 'fake'))
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/unit/car_test.rb | test/unit/car_test.rb | ################################################################################
require('test_helper')
################################################################################
class CarTest < ActiveSupport::TestCase
# No logic to test yet.
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/unit/refuel_test.rb | test/unit/refuel_test.rb | ################################################################################
require('test_helper')
################################################################################
class RefuelTest < ActiveSupport::TestCase
##############################################################################
test "make sure composed_of money is working" do
refuel = Refuel.new
refuel.price_cents = 100
assert_equal("1.00".to_money, refuel.price)
refuel.price = "2.50"
assert_equal("2.50".to_money, refuel.price)
assert_equal(refuel.price_cents, 250)
end
##############################################################################
test "preceding and following methods" do
make_a_bunch_of_refuels
refuel = @car.refuels.where(:refueled_at => @dates[2]).first
assert(refuel)
preceding = refuel.preceding
assert(preceding)
assert_equal(@dates[1], preceding.refueled_at)
following = refuel.following
assert(following)
assert_equal(@dates[3], following.refueled_at)
end
##############################################################################
test "caching of mpg and distance" do
make_a_bunch_of_refuels
# The first refuel won't have any mpg info
first = @car.refuels.where(:refueled_at => @dates[0]).first
assert(first)
assert(first.mpg.blank?)
assert(first.distance.blank?)
# All others should have the same mpg and distance because we
# created them that way.
(1...@dates.size).each do |index|
refuel = @car.refuels.where(:refueled_at => @dates[index]).first
assert(refuel)
assert_equal(100, refuel.distance)
assert_equal("9.62", "%.2f" % [refuel.mpg])
end
end
##############################################################################
private
##############################################################################
def make_a_bunch_of_refuels
@dates = [
'2011-08-01 10:30:00',
'2011-08-06 14:51:00',
'2011-09-01 13:16:00',
'2011-09-16 14:56:00',
'2011-10-01 20:01:00',
].map {|date| Time.parse(date)}
@car = FactoryGirl.create(:car)
odometer = 160809
distance = 100
@dates.each do |date|
@car.refuels.create!(:refueled_at => date,
:odometer => odometer,
:gallons => 10.4,
:price => '50.24')
odometer += distance
end
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/unit/helpers/cars_helper_test.rb | test/unit/helpers/cars_helper_test.rb | require 'test_helper'
class CarsHelperTest < ActionView::TestCase
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/unit/helpers/sessions_helper_test.rb | test/unit/helpers/sessions_helper_test.rb | require 'test_helper'
class SessionsHelperTest < ActionView::TestCase
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/unit/helpers/refuels_helper_test.rb | test/unit/helpers/refuels_helper_test.rb | require 'test_helper'
class RefuelsHelperTest < ActionView::TestCase
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/functional/sessions_controller_test.rb | test/functional/sessions_controller_test.rb | ################################################################################
require('test_helper')
################################################################################
class SessionsControllerTest < ActionController::TestCase
##############################################################################
test "can log in with a valid password" do
user = FactoryGirl.create(:user)
post(:create, :user => {:email => user.email, :password => 'fubar'})
assert_response(:redirect)
assert_redirected_to(root_path)
assert_equal(user.id, session[:user_id])
end
##############################################################################
test "cannot log in with a bad password" do
user = FactoryGirl.create(:user)
post(:create, :user => {:email => user.email, :password => 'BAD'})
assert_response(:success) # the login form was rendered
assert_template(:new)
assert(session[:user_id].blank?)
end
##############################################################################
test "user can log out" do
user = FactoryGirl.create(:user)
# GET /sessions/destroy with no params and a session that
# indicates a logged in user.
get(:destroy, {}, {:user_id => user.id})
assert_response(:redirect)
assert_redirected_to(root_path)
assert(session[:user_id].blank?)
end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/functional/refuels_controller_test.rb | test/functional/refuels_controller_test.rb | require 'test_helper'
class RefuelsControllerTest < ActionController::TestCase
# test "the truth" do
# assert true
# end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/test/functional/cars_controller_test.rb | test/functional/cars_controller_test.rb | require 'test_helper'
class CarsControllerTest < ActionController::TestCase
# test "the truth" do
# assert true
# end
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/application.rb | config/application.rb | require File.expand_path('../boot', __FILE__)
require 'rails/all'
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 Example
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 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
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/environment.rb | config/environment.rb | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Example::Application.initialize!
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/routes.rb | config/routes.rb | ################################################################################
# To see a complete list of all routes use the following command:
#
# rake routes
#
Example::Application.routes.draw do
##############################################################################
# Create all the default routes for the cars controller.
resources(:cars) do
# Refuels is a nested resource, you have to get to them through
# the cars resource. This affects URLs and the URL generators.
# After adding this try running `rake routes`.
resources(:refuels)
end
##############################################################################
# Default and custom routes for sessions
resources(:sessions)
match('/login' => 'sessions#new', :as => :login)
match('/logout' => 'sessions#destroy', :as => :logout)
##############################################################################
# Route '/' to the cars controller.
root(:to => 'cars#index')
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/boot.rb | 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'])
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/initializers/session_store.rb | config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
Example::Application.config.session_store :cookie_store, :key => '_example_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")
# Example::Application.config.session_store :active_record_store
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/initializers/wrap_parameters.rb | 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
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/initializers/inflections.rb | 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
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/initializers/backtrace_silencers.rb | 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!
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/initializers/mime_types.rb | 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
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/initializers/secret_token.rb | 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.
Example::Application.config.secret_token = 'a940a1d31811250b4f1f130aa92925f0abccd7070f0f38a06e22e96d73a8b833bd4976257f15ae0e2bca1b7da8e185e1cecf5bea54b14863c7c87c7da77ff3de'
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/environments/test.rb | config/environments/test.rb | Example::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"
# Log error messages when you accidentally call methods on nil
config.whiny_nils = true
# 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
# Use SQL instead of Active Record's schema dumper when creating the test 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
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/environments/development.rb | config/environments/development.rb | Example::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
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# 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
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
devalot/ror-example | https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/config/environments/production.rb | config/environments/production.rb | Example::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 Rails.root.join("public/assets")
# 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
# Use a different logger for distributed setups
# config.logger = 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
end
| ruby | Unlicense | 2acf777ef9939b6f53c0387f9b2620f76016ae0c | 2026-01-04T17:54:41.674960Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/dataflow.rb | dataflow.rb | require 'monitor'
module Dataflow
VERSION = "0.3.1"
class << self
attr_accessor :forker
end
self.forker = Thread.method(:fork)
def self.included(cls)
class << cls
def declare(*readers)
readers.each do |name|
class_eval <<-RUBY
def #{name}
return @__dataflow_#{name}__ if defined? @__dataflow_#{name}__
Variable::LOCK.synchronize { @__dataflow_#{name}__ ||= Variable.new }
end
RUBY
end
end
end
end
def local(&block)
return Variable.new unless block_given?
vars = Array.new(block.arity) { Variable.new }
block.call *vars
end
def unify(variable, value)
variable.__unify__ value
end
def by_need(&block)
Variable.new &block
end
def barrier(*variables)
variables.each{|v| v.__wait__ }
end
def flow(output=nil, &block)
Dataflow.forker.call do
result = block.call
unify output, result if output
end
end
def need_later(&block)
local do |future|
flow(future) { block.call }
future
end
end
extend self
# Note that this class uses instance variables directly rather than nicely
# initialized instance variables in get/set methods for memory and
# performance reasons
class Variable
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
LOCK = Monitor.new
def initialize(&block) @__trigger__ = block if block_given? end
# Lazy-load conditions to be nice on memory usage
def __binding_condition__() @__binding_condition__ ||= LOCK.new_cond end
def __unify__(value)
LOCK.synchronize do
__activate_trigger__ if @__trigger__
if @__bound__
return @__value__.__unify__(value) if @__value__.__dataflow__? rescue nil
raise UnificationError, "#{@__value__.inspect} != #{value.inspect}" if self != value
else
@__value__ = value
@__bound__ = true
__binding_condition__.broadcast # wakeup all method callers
@__binding_condition__ = nil # GC
end
end
@__value__
end
def __activate_trigger__
@__value__ = @__trigger__.call
@__bound__ = true
@__trigger__ = nil # GC
end
def __wait__
LOCK.synchronize do
unless @__bound__
if @__trigger__
__activate_trigger__
else
__binding_condition__.wait
end
end
end unless @__bound__
end
def method_missing(name, *args, &block)
return "#<Dataflow::Variable:#{__id__} unbound>" if !@__bound__ && name == :inspect
__wait__
@__value__.__send__(name, *args, &block)
end
def __dataflow__?
true
end
end
UnificationError = Class.new StandardError
end
require "#{File.dirname(__FILE__)}/dataflow/enumerable"
require "#{File.dirname(__FILE__)}/dataflow/port"
require "#{File.dirname(__FILE__)}/dataflow/actor"
require "#{File.dirname(__FILE__)}/dataflow/future_queue"
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/dataflow/future_queue.rb | dataflow/future_queue.rb | module Dataflow
class FutureQueue
include Dataflow
declare :push_port, :pop_port
def initialize
local do |pushed, popped|
unify push_port, Dataflow::Port.new(pushed)
unify pop_port, Dataflow::Port.new(popped)
Thread.new {
loop do
barrier pushed.head, popped.head
unify popped.head, pushed.head
pushed, popped = pushed.tail, popped.tail
end
}
end
end
def push(x) push_port.send x end
def pop(x) pop_port.send x end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/dataflow/port.rb | dataflow/port.rb | require 'thread'
module Dataflow
class Port
include Dataflow
LOCK = Mutex.new
class Stream
include Dataflow
declare :head, :tail
# Defining each allows us to use the enumerable mixin
# None of the list can be garbage collected less the head is
# garbage collected, so it will grow indefinitely even though
# the function isn't recursive.
include Enumerable
def each
s = self
loop do
yield s.head
s = s.tail
end
end
# Backported Enumerable#take for any 1.8.6 compatible Ruby
unless method_defined?(:take)
def take(num)
result = []
each_with_index do |x, i|
return result if num == i
result << x
end
end
end
end
# Create a stream object, bind it to the input variable
# Instance variables are necessary because @end is state
def initialize(x)
@end = Stream.new
unify x, @end
end
# This needs to be synchronized because it uses @end as state
def send value
LOCK.synchronize do
unify @end.head, value
unify @end.tail, Stream.new
@end = @end.tail
end
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/dataflow/equality.rb | dataflow/equality.rb | # The purpose of this file is to make equality use method calls in as
# many Ruby implementations as possible. If method calls are used,
# then equality operations using dataflow variaables becomes seemless
# I realize overriding core classes is a pretty nasty hack, but if you
# have a better idea that also passes the equality_specs then I'm all
# ears. Please run the rubyspec before committing changes to this file.
class Object
def ==(other)
object_id == other.object_id
end
end
class Symbol
def ==(other)
object_id == other.object_id
end
end
class Regexp
def ==(other)
other.is_a?(Regexp) &&
casefold? == other.casefold? &&
kcode == other.kcode &&
options == other.options &&
source == other.source
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/dataflow/actor.rb | dataflow/actor.rb | module Dataflow
class Actor < Thread
def initialize(&block)
@stream = Variable.new
@port = Port.new(@stream)
# Run this block in a new thread
super { instance_eval &block }
end
def send message
@port.send message
end
private
def receive
result = @stream.head
@stream = @stream.tail
result
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/dataflow/enumerable.rb | dataflow/enumerable.rb | module Dataflow
code = <<-RUBY
def map_later
map do |x|
Dataflow.need_later { yield x }
end
end
def map_barrier(&blk)
result = map_later(&blk)
Dataflow.barrier *result
result
end
def map_needed
map do |x|
Dataflow.by_need { yield x }
end
end
RUBY
module_eval "module Enumerable\n#{code}\n end"
module_eval <<-RUBY
def self.enumerable!
module_eval "module ::Enumerable\n#{code}\n end"
end
RUBY
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/port_spec.rb | spec/port_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'Syncronously sending to a Port' do
it 'extends the length of the stream and preserves order' do
local do |port, stream|
unify port, Dataflow::Port.new(stream)
port.send 1
port.send 2
stream.take(2).should == [1, 2]
port.send 3
stream.take(3).should == [1, 2, 3]
end
end
end
describe 'Asyncronously sending to a Port' do
it 'extends the length of the stream and does not preserve order' do
local do |port, stream|
unify port, Dataflow::Port.new(stream)
Thread.new {port.send 2}
Thread.new {port.send 8}
Thread.new {port.send 1024}
stream.take(3).sort.should == [2, 8, 1024]
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/inspect_spec.rb | spec/inspect_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe "An unbound variable" do
it "should be inspectable for debugging purposes" do
local do |unbound|
unbound.inspect.should =~ /#<Dataflow::Variable:-?\d+ unbound>/
end
end
end
describe "An bound variable" do
it "should proxy inspect" do
local do |bound|
bound.inspect
unify bound, "str"
bound.should == "str"
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/need_later_spec.rb | spec/need_later_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'A need_later expression' do
it 'returns a future to be calculated later' do
local do |x, y, z|
unify y, need_later { 4 }
unify z, need_later { x + y }
unify x, need_later { 3 }
z.should == 7
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/future_queue_spec.rb | spec/future_queue_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'A future queue' do
it 'accepts synchronous pushes and pops' do
local do |queue, first, second, third|
unify queue, Dataflow::FutureQueue.new
queue.pop first
queue.pop second
queue.push 1
queue.push 2
queue.push 3
queue.pop third
[first, second, third].should == [1, 2, 3]
end
end
it 'accepts asynchronous pushes and pops' do
local do |queue, first, second, third|
unify queue, Dataflow::FutureQueue.new
Thread.new { queue.pop first }
Thread.new { queue.pop second }
Thread.new { queue.push 1 }
Thread.new { queue.push 2 }
Thread.new { queue.push 3 }
Thread.new { queue.pop third }
[first, second, third].sort.should == [1, 2, 3]
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/forker_spec.rb | spec/forker_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'Setting a customer forker' do
before(:all) do
@original_forker = Dataflow.forker
Dataflow.forker = Class.new do
def self.synchronous_forker(&block)
block.call
end
end.method(:synchronous_forker)
end
after(:all) do
Dataflow.forker = @original_forker
end
it 'uses the custom forker in #flow' do
local do |my_var|
flow(my_var) { 1337 }
my_var.should == 1337
end
end
it 'uses the custom forker in #need_later' do
my_var = need_later { 1337 }
my_var.should == 1337
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/anonymous_variables_spec.rb | spec/anonymous_variables_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'Using an anonymous variable' do
it 'works with Variable instances' do
container = [Dataflow::Variable.new]
unify container.first, 1337
container.first.should == 1337
end
it 'works with Dataflow.local' do
container = [Dataflow.local]
unify container.first, 1337
container.first.should == 1337
end
it 'works with #local' do
container = [local]
unify container.first, 1337
container.first.should == 1337
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/barrier_spec.rb | spec/barrier_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'A barrier' do
it 'waits for variables to be bound before continuing' do
local do |x, y, barrier_broken|
Thread.new do
barrier x, y
unify barrier_broken, true
end
Thread.new { unify x, :x }
Thread.new { unify y, :y }
barrier_broken.should be_true
end
end
it 'continues for variables that are already bound' do
local do |x, y, barrier_broken|
unify x, :x
unify y, :y
barrier x, y
unify barrier_broken, true
barrier_broken.should be_true
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/flow_spec.rb | spec/flow_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'Using flow without a parameter' do
it 'works like normal threads' do
local do |big_cat, small_cat|
flow { unify big_cat, small_cat.upcase }
unify small_cat, 'cat'
big_cat.should == 'CAT'
end
end
end
describe 'Using flow with a parameter' do
it 'binds the parameter to the last line of the block' do
local do |big_cat, small_cat, output|
flow(output) do
unify big_cat, small_cat.upcase
'returned'
end
unify small_cat, 'cat'
big_cat.should == 'CAT'
output.should == 'returned'
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/enumerable_spec.rb | spec/enumerable_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe Dataflow::Enumerable do
it '#map_later combines map & need_later' do
[1, 2, 3].map_later do |x|
x.succ
end.should == [2, 3, 4]
end
it '#map_barrier combines map, need_later, & barrier' do
[1, 2, 3].map_barrier do |x|
x.succ
end.should == [2, 3, 4]
end
it '#map_needed combines map & by_need' do
x = []
y = []
enum = [x, y]
enum = enum.map_needed{|ar| ar << 1337; ar }
x.should be_empty
y.should be_empty
enum.size.should == 2
enum.last.should == [1337]
x.should be_empty
y.should == [1337]
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/equality_spec.rb | spec/equality_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'Unifying a bound value' do
[nil, true, false,
:sym, "str", /regex/,
3, 2.0,
Object.new, Class.new.new,
[], {}].each do |type|
describe "for #{type.class} instances" do
it 'passes unification for an object of equal value' do
local do |var, var2|
unify var, type
var.should == type
type.should == var
lambda {unify var, type}.should_not raise_error
unify var2, type
var.should == var2
var2.should == var
lambda {unify var, var2}.should_not raise_error
end
end
it 'fails unification for an object of inequal value' do
different = Object.new
local do |var, var2|
unify var, type
var.should_not == different
different.should_not == var
lambda {unify var, different}.should raise_error(Dataflow::UnificationError)
unify var2, different
var.should_not == var2
var2.should_not == var
lambda {unify var, different}.should raise_error(Dataflow::UnificationError)
end
end
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/actor_spec.rb | spec/actor_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'Syncronously sending to an Actor' do
it 'passes in each message received and preserves order' do
local do |port, stream, actor|
unify port, Dataflow::Port.new(stream)
unify actor, Dataflow::Actor.new { 3.times { port.send receive } }
actor.send 1
actor.send 2
stream.take(2).should == [1, 2]
actor.send 3
stream.take(3).should == [1, 2, 3]
end
end
end
describe 'Asyncronously sending to an Actor' do
it 'passes in each message received and preserves order' do
local do |port, stream, actor|
unify port, Dataflow::Port.new(stream)
unify actor, Dataflow::Actor.new { 3.times { port.send receive } }
Thread.new {actor.send 2}
Thread.new {actor.send 8}
Thread.new {actor.send 1024}
stream.take(3).sort.should == [2, 8, 1024]
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/dataflow_spec.rb | spec/dataflow_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
context 'Using "local" for local variables' do
describe 'An unbound Variable' do
it 'suspends if an unbound variable has a method called on it until it is bound' do
local do |big_cat, small_cat|
Thread.new { unify big_cat, small_cat.upcase }
unify small_cat, 'cat'
big_cat.should == 'CAT'
end
end
it 'suspends if an unbound variable has a method called on it until it is bound with nil' do
local do |is_nil, var_nil|
Thread.new { unify is_nil, var_nil.nil? }
unify var_nil, nil
is_nil.should be_true
end
end
it 'suspends if an unbound variable has a method called on it until it is bound (with nested local variables)' do
local do |small_cat|
local do |big_cat|
Thread.new { unify big_cat, small_cat.upcase }
unify small_cat, 'cat'
big_cat.should == 'CAT'
end
end
end
it 'performs order-determining concurrency' do
local do |x, y, z|
Thread.new { unify y, x + 2 }
Thread.new { unify z, y + 3 }
Thread.new { unify x, 1 }
z.should == 6
end
end
it 'binds on unification' do
local do |animal|
unify animal, 'cat'
animal.should == 'cat'
end
end
end
end
describe 'A bound Variable' do
it 'does not complain when unifying with an equal object' do
lambda do
local do |animal|
unify animal, 'cat'
unify animal, 'cat'
end
end.should_not raise_error
end
it 'does not complain when unifying with an unequal object when shadowing' do
lambda do
local do |animal|
unify animal, 'cat'
local do |animal|
unify animal, 'dog'
end
end
end.should_not raise_error
end
it 'complains when unifying with an unequal object' do
lambda do
local do |animal|
unify animal, 'cat'
unify animal, 'dog'
end
end.should raise_error(Dataflow::UnificationError)
end
end
context 'Using "declare" for object-specific read-only attributes' do
class Store
include Dataflow
declare :animal, :big_cat, :small_cat, :x, :y, :z, :is_nil, :var_nil
end
before { @store = Store.new }
describe 'An unbound Variable' do
it 'suspends if an unbound variable has a method called on it until it is bound' do
Thread.new { unify @store.big_cat, @store.small_cat.upcase }
unify @store.small_cat, 'cat'
@store.big_cat.should == 'CAT'
end
it 'suspends if an unbound variable has a method called on it until it is bound with nil' do
Thread.new { unify @store.is_nil, @store.var_nil.nil? }
unify @store.var_nil, nil
@store.is_nil.should be_true
end
it 'performs order-determining concurrency' do
Thread.new { unify @store.y, @store.x + 2 }
Thread.new { unify @store.z, @store.y + 3 }
Thread.new { unify @store.x, 1 }
@store.z.should == 6
end
it 'binds on unification' do
unify @store.animal, 'cat'
@store.animal.should == 'cat'
end
end
describe 'A bound Variable' do
it 'does not complain when unifying with an equal object' do
lambda do
unify @store.animal, 'cat'
unify @store.animal, 'cat'
end.should_not raise_error
end
it 'complains when unifying with an unequal object' do
lambda do
unify @store.animal, 'cat'
unify @store.animal, 'dog'
end.should raise_error(Dataflow::UnificationError)
end
end
end
describe 'Binding a variable that proxies through another' do
it 'binds through successfully' do
local do |x, y|
lambda do
unify x, y
unify x, 1337
x.should == 1337
y.should == 1337
end.should_not raise_error
end
end
end
describe 'Using static/module method' do
it 'works like the mixin versions' do
Dataflow.local do |big_cat, small_cat|
Thread.new { Dataflow.unify big_cat, small_cat.upcase }
Dataflow.unify small_cat, 'cat'
big_cat.should == 'CAT'
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/by_need_spec.rb | spec/by_need_spec.rb | require "#{File.dirname(__FILE__)}/spec_helper"
describe 'A by_need expression' do
describe 'when a method is called on it' do
it 'binds its variable' do
local do |x, y, z|
Thread.new { unify y, by_need { 4 } }
Thread.new { unify z, x + y }
Thread.new { unify x, by_need { 3 } }
z.should == 7
end
end
end
describe 'when a bound variable is unified to it' do
it 'passes unififcation for equal values' do
local do |x|
unify x, by_need { 1 }
unify x, 1
x.should == 1
y = by_need { 1 }
unify y, 1
y.should == 1
end
end
it 'fails unififcation for unequal values' do
local do |x|
unify x, by_need { 1 }
lambda { unify x, 2 }.should raise_error(Dataflow::UnificationError)
y = by_need { 1 }
lambda { unify y, 2 }.should raise_error(Dataflow::UnificationError)
end
end
describe 'when it is unified to a bound variable' do
it 'passes unififcation for equal values' do
local do |x|
unify x, 1
unify x, by_need { 1 }
x.should == 1
end
end
it 'fails unification for unequal values' do
local do |x|
unify x, 1
lambda { unify x, by_need { 2 } }.should raise_error(Dataflow::UnificationError)
end
end
end
end
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/spec/spec_helper.rb | spec/spec_helper.rb | require 'rubygems'
require 'spec'
require "#{File.dirname(__FILE__)}/../dataflow"
require "#{File.dirname(__FILE__)}/../dataflow/equality"
Thread.abort_on_exception = true
Spec::Runner.configure do |config|
config.include Dataflow
end
Dataflow.enumerable!
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/future_queue.rb | examples/future_queue.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
local do |queue, first, second|
unify queue, Dataflow::FutureQueue.new
queue.pop first
queue.push 1
queue.push 2
queue.pop second
puts "first: #{first}, second: #{second}"
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/local_variables.rb | examples/local_variables.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
local do |x, y, z|
# notice how the order automatically gets resolved
Thread.new { unify y, x + 2 }
Thread.new { unify z, y + 3 }
Thread.new { unify x, 1 }
puts z
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/instance_variables.rb | examples/instance_variables.rb | require "#{File.dirname(__FILE__)}/../dataflow"
class AnimalHouse
include Dataflow
declare :small_cat, :big_cat
def fetch_big_cat
Thread.new { unify big_cat, small_cat.upcase }
unify small_cat, 'cat'
big_cat
end
end
puts AnimalHouse.new.fetch_big_cat
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/connection_protector.rb | examples/connection_protector.rb | require "#{File.dirname(__FILE__)}/../dataflow"
class ThreadUnsafeConnection
def initialize() @used = 0 end
def value
@used += 1
end
end
class ConnectionProtector
def initialize
@queue = Dataflow::FutureQueue.new
@queue.push ThreadUnsafeConnection.new
end
def protect(&block)
Dataflow.local do |connection|
@queue.pop connection
block.call connection
@queue.push connection
end
end
end
def self.sometimes(num, connection)
if num%2 == 0
"#{num}:#{connection.value}"
else
"connection not used!"
end
end
protector = ConnectionProtector.new
19.times {|i| Thread.new {
protector.protect do |connection|
puts sometimes(i, connection)
end
} }
protector.protect do |connection|
puts sometimes(20, connection)
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/port_http_gets.rb | examples/port_http_gets.rb | require "#{File.dirname(__FILE__)}/../dataflow"
require 'net/http'
include Dataflow
# Be gentle running this one
Thread.abort_on_exception = true
local do |port, stream, branding_occurences, number_of_mentions|
unify port, Dataflow::Port.new(stream)
10.times { Thread.new(port) {|p| p.send Net::HTTP.get_response(URI.parse("http://www.cuil.com/search?q=#{rand(1000)}")).body } }
Thread.new { unify branding_occurences, stream.take(10).map {|http_body| http_body.scan /cuil/ } }
Thread.new { unify number_of_mentions, branding_occurences.map {|occurences| occurences.length } }
puts number_of_mentions.inspect
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/data_driven.rb | examples/data_driven.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
local do |stream, doubles, triples, squares|
unify stream, Array.new(5) { Dataflow::Variable.new }
Thread.new { unify doubles, stream.map {|n| n*2 } }
Thread.new { unify triples, stream.map {|n| n*3 } }
Thread.new { unify squares, stream.map {|n| n**2 } }
Thread.new { stream.each {|x| unify x, rand(100) } }
puts "original: #{stream.inspect}"
puts "doubles: #{doubles.inspect}"
puts "triples: #{triples.inspect}"
puts "squares: #{squares.inspect}"
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/ring.rb | examples/ring.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
# Send M messages each along a ring of N nodes
N = 4
M = 2
actors = Array.new(N) { Dataflow::Variable.new }
N.times do |n|
unify actors[n], Actor.new {
M.times do |m|
receive
puts "[#{n} #{m}]"
actors[(n+1) % N].send :msg
end
puts "[#{n}] done"
}
end
actors.first.send :msg
actors.each { |x| x.join }
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/port_send.rb | examples/port_send.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
local do |port, stream|
unify port, Dataflow::Port.new(stream)
Thread.new {port.send 2}
Thread.new {port.send 8}
Thread.new {port.send 1024}
puts stream.take(3).sort.inspect
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/flow.rb | examples/flow.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
# flow without parameters
local do |x|
flow do
# other stuff
unify x, 1337
end
puts x
end
# flow with an output parameter
local do |x|
flow(x) do
# other stuff
1337
end
puts x
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/laziness.rb | examples/laziness.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
local do |x, y, z|
Thread.new { unify y, by_need { 4 } }
Thread.new { unify z, x + y }
Thread.new { unify x, by_need { 3 } }
puts z
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/dataflow_http_gets.rb | examples/dataflow_http_gets.rb | require "#{File.dirname(__FILE__)}/../dataflow"
require 'net/http'
include Dataflow
# Be gentle running this one
Thread.abort_on_exception = true
local do |stream, branding_occurences, number_of_mentions|
unify stream, Array.new(10) { Dataflow::Variable.new }
stream.each {|s| Thread.new(s) {|v| unify v, Net::HTTP.get_response(URI.parse("http://www.cuil.com/search?q=#{rand(1000)}")).body } }
Thread.new { unify branding_occurences, stream.map {|http_body| http_body.scan /cuil/ } }
Thread.new { unify number_of_mentions, branding_occurences.map {|occurences| occurences.length } }
puts number_of_mentions.inspect
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/future_http_gets.rb | examples/future_http_gets.rb | require "#{File.dirname(__FILE__)}/../dataflow"
require 'net/http'
include Dataflow
# Be gentle running this one
Thread.abort_on_exception = true
local do |stream, branding_occurences, number_of_mentions|
unify stream, Array.new(10) { need_later { Net::HTTP.get_response(URI.parse("http://www.cuil.com/search?q=#{rand(1000)}")).body } }
unify branding_occurences, need_later { stream.map {|http_body| http_body.scan /cuil/ } }
unify number_of_mentions, need_later { branding_occurences.map {|occurences| occurences.length } }
puts number_of_mentions.inspect
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/messages.rb | examples/messages.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
Ping = Actor.new {
3.times {
case receive
when "Ping"
puts "Ping"
Pong.send "Pong"
end
}
}
Pong = Actor.new {
3.times {
case receive
when "Pong"
puts "Pong"
Ping.send "Ping"
end
}
}
Ping.send "Ping"
Ping.join
Pong.join
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
larrytheliquid/dataflow | https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/examples/barrier.rb | examples/barrier.rb | require "#{File.dirname(__FILE__)}/../dataflow"
include Dataflow
local do |lock1, lock2|
flow { unify lock1, :unlocked }
flow { unify lock2, :unlocked }
barrier lock1, lock2
puts "Barrier broken!"
end
| ruby | MIT | c856552bbc0fc9e64b2b13a08239cba985874eaf | 2026-01-04T17:54:36.790117Z | false |
harryw/raft | https://github.com/harryw/raft/blob/2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c/features/support/env.rb | features/support/env.rb | require 'raft'
require 'raft/goliath'
require 'rspec'
require 'em-synchrony/em-http'
Around do |_, block|
EM.synchrony {block.call}
end
| ruby | MIT | 2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c | 2026-01-04T17:54:42.497228Z | false |
harryw/raft | https://github.com/harryw/raft/blob/2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c/features/step_definitions/node_steps.rb | features/step_definitions/node_steps.rb | Before do
@goliaths = {}
@config = Raft::Config.new(
Raft::Goliath.rpc_provider(Proc.new {|node_id, message| URI("http://localhost:#{node_id}/#{message}")}),
Raft::Goliath.async_provider,
1.5, #election_timeout seconds
1.0, #election_splay seconds
0.2, #update_interval seconds
1.0) #heartbeat_interval second
@cluster = Raft::Cluster.new
end
After do
@goliaths.values.each {|goliath| goliath.stop}
EventMachine.stop
end
def create_node_on_port(port)
@cluster.node_ids << port
node = Raft::Node.new(port, @config, @cluster)
@goliaths[port] = Raft::Goliath.new(node) {|command| puts "executing command #{command}"}
@goliaths[port].start(port: port)
end
def role_code(role)
case role
when /leader/i
Raft::Node::LEADER_ROLE
when /follower/i
Raft::Node::FOLLOWER_ROLE
when /candidate/i
Raft::Node::CANDIDATE_ROLE
end
end
def clear_log_on_node(node)
log = node.persistent_state.log
log.clear if log.any?
end
def update_log_on_node(node, new_log)
clear_log_on_node(node)
log = node.persistent_state.log
new_log.each {|log_entry| log << log_entry}
end
def consistent_logs?
first_node = @goliaths.values.first.node
@goliaths.values.map(&:node).all? do |node|
cons = first_node.persistent_state.log == node.persistent_state.log
cons &&= first_node.temporary_state.commit_index == node.temporary_state.commit_index
cons && first_node.temporary_state.commit_index == first_node.persistent_state.log.last.index
end
end
Given(/^there is a node on port (\d+)$/) do |port|
create_node_on_port(port)
end
When(/^I send the command "(.*?)" to the node on port (\d+)$/) do |command, port|
http = EventMachine::HttpRequest.new("http://localhost:#{port}/command").apost(
:body => %Q({"command": "#{command}"}),
:head => { 'Content-Type' => 'application/json' })
http.timeout 10
http.errback {|*args| fail "request error"}#": #{http.pretty_inspect}\n\nnodes: #{@goliaths.values.map {|g|g.node}.pretty_inspect}"}
#puts "EM.threadpool.count:#{EM.threadpool.count}"
EM::Synchrony.sync(http)
#puts "EM.threadpool.count:#{EM.threadpool.count}"
#fail "request invalid" if http.nil?
fail "request unfinished: #{http}" unless http.finished?
#fail "request unfinished (http = #{http.pretty_inspect})" unless http.finished?
end
Then(/^the node on port (\d+) should be in the "(.*?)" role$/) do |port, role|
@goliaths[port].node.role.should == role_code(role)
end
Given(/^there are nodes on the following ports:$/) do |table|
table.raw.each do |row|
create_node_on_port(row[0])
end
end
Then(/^just one of the nodes should be in the "(.*?)" role$/) do |role|
@goliaths.values.select {|goliath| goliath.node.role == role_code(role)}
end
Given(/^all the nodes have empty logs$/) do
@goliaths.values.each do |goliath|
clear_log_on_node(goliath.node)
end
end
Given(/^the node on port (\d+) has an empty log$/) do |port|
clear_log_on_node(@goliaths[port].node)
end
Given(/^the node on port (\d+) has the following log:$/) do |port, table|
log = table.hashes.map {|row| Raft::LogEntry.new(row['term'].to_i, row['index'].to_i, row['command'])}.to_a
update_log_on_node(@goliaths[port].node, log)
end
Given(/^the node on port (\d+)'s current term is (\d+)$/) do |port, term|
@goliaths[port].node.persistent_state.current_term = term.to_i
end
Then(/^a single node on one of the following ports should be in the "(.*?)" role:$/) do |role, table|
begin
table.raw.map {|row| row[0]}.select {|port| @goliaths[port].node.role == role_code(role)}.should have(1).item
rescue
@goliaths.values.map(&:node).each {|node| puts "Node #{node.id}: role #{node.role}"}
raise
end
end
Then(/^the node on port (\d+) should have the following log:$/) do |port, table|
log = table.hashes.map {|row| Raft::LogEntry.new(row['term'].to_i, row['index'].to_i, row['command'])}.to_a
@goliaths[port].node.persistent_state.log.should == log
end
Then(/^the node on port (\d+) should have the following commands in the log:$/) do |port, table|
commands = table.raw.map(&:first)
@goliaths[port].node.persistent_state.log.map(&:command).should == commands
end
When(/^I await full replication$/) do
f = Fiber.current
# Allow up to 10 seconds
timeout_timer = EventMachine.add_timer(10) do
f.resume
end
# Check every 1 second
check_timer = EventMachine.add_periodic_timer(1) do
if consistent_logs?
f.resume
end
end
Fiber.yield
EventMachine.cancel_timer(check_timer)
EventMachine.cancel_timer(timeout_timer)
end
Given(/^the node port port (\d+) has as commit index of (\d+)$/) do |port, commit_index|
@goliaths[port].node.temporary_state.commit_index = commit_index.to_i
end
| ruby | MIT | 2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c | 2026-01-04T17:54:42.497228Z | false |
harryw/raft | https://github.com/harryw/raft/blob/2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c/lib/raft.rb | lib/raft.rb | require 'delegate'
module Raft
Config = Struct.new(:rpc_provider, :async_provider, :election_timeout, :election_splay, :update_interval, :heartbeat_interval)
class Cluster
attr_reader :node_ids
def initialize(*node_ids)
@node_ids = node_ids
end
def quorum
@node_ids.count / 2 + 1 # integer division rounds down
end
end
class LogEntry
attr_reader :term, :index, :command
def initialize(term, index, command)
@term, @index, @command = term, index, command
end
def ==(other)
[:term, :index, :command].all? do |attr|
self.send(attr) == other.send(attr)
end
end
def eql?(other)
self == other
end
def hash
[:term, :index, :command].reduce(0) do |h, attr|
h ^= self.send(attr)
end
end
end
class Log < DelegateClass(Array)
def last(*args)
self.any? ? super(*args) : LogEntry.new(nil, nil, nil)
end
end
class PersistentState #= Struct.new(:current_term, :voted_for, :log)
attr_reader :current_term, :voted_for, :log
def initialize
@current_term = 0
@voted_for = nil
@log = Log.new([])
end
def current_term=(new_term)
raise 'cannot restart an old term' unless @current_term < new_term
@current_term = new_term
@voted_for = nil
end
def voted_for=(new_votee)
raise 'cannot change vote for this term' unless @voted_for.nil?
@voted_for = new_votee
end
def log=(new_log)
@log = Log.new(new_log)
end
end
class TemporaryState
attr_reader :commit_index
attr_accessor :leader_id
def initialize(commit_index, leader_id)
@commit_index, @leader_id = commit_index, leader_id
end
def commit_index=(new_commit_index)
raise 'cannot uncommit log entries' unless @commit_index.nil? || @commit_index <= new_commit_index
@commit_index = new_commit_index
end
end
class LeadershipState
def followers
@followers ||= {}
end
attr_reader :update_timer
def initialize(update_interval)
@update_timer = Timer.new(update_interval)
end
end
FollowerState = Struct.new(:next_index, :succeeded)
RequestVoteRequest = Struct.new(:term, :candidate_id, :last_log_index, :last_log_term)
#class RequestVoteRequest < Struct.new(:term, :candidate_id, :last_log_index, :last_log_term)
# def term; @term.to_i; end
# def last_log_index; @last_log_index.to_i; end
# def last_log_term; @last_log_term.to_i; end
#end
RequestVoteResponse = Struct.new(:term, :vote_granted)
#class RequestVoteResponse < Struct.new(:term, :vote_granted)
# def term; @term.to_i; end
#end
AppendEntriesRequest = Struct.new(:term, :leader_id, :prev_log_index, :prev_log_term, :entries, :commit_index)
AppendEntriesResponse = Struct.new(:term, :success)
CommandRequest = Struct.new(:command)
CommandResponse = Struct.new(:success)
class RpcProvider
def request_votes(request, cluster)
raise "Your RpcProvider subclass must implement #request_votes"
end
def append_entries(request, cluster)
raise "Your RpcProvider subclass must implement #append_entries"
end
def append_entries_to_follower(request, node_id)
raise "Your RpcProvider subclass must implement #append_entries_to_follower"
end
def command(request, node_id)
raise "Your RpcProvider subclass must implement #command"
end
end
class AsyncProvider
def await
raise "Your AsyncProvider subclass must implement #await"
end
end
class Timer
def initialize(interval, splay=0.0)
@interval = interval.to_f
@splay = splay.to_f
@start = Time.now - @interval + (rand * @splay)
end
def splayed_interval
(@interval + (rand * @splay))#.tap {|t|STDOUT.write("\nsplayed interval is #{t}\n")}
end
def reset!
@start = Time.now + splayed_interval
#STDOUT.write("\ntimer will elapse at #{timeout.strftime('%H:%M:%S:%L')} (timeout is #{timeout.class})\n")
end
def timeout
@start + @interval
end
def timed_out?
#STDOUT.write("\ntime is #{Time.now.strftime('%M:%S:%L')}\n")
Time.now > timeout
end
end
class Node
attr_reader :id
attr_reader :role
attr_reader :config
attr_reader :cluster
attr_reader :persistent_state
attr_reader :temporary_state
attr_reader :election_timer
FOLLOWER_ROLE = 0
CANDIDATE_ROLE = 1
LEADER_ROLE = 2
def initialize(id, config, cluster, commit_handler=nil, &block)
@id = id
@role = FOLLOWER_ROLE
@config = config
@cluster = cluster
@persistent_state = PersistentState.new
@temporary_state = TemporaryState.new(nil, nil)
@election_timer = Timer.new(config.election_timeout, config.election_splay)
@commit_handler = commit_handler || (block.to_proc if block_given?)
end
def update
return if @updating
@updating = true
indent = "\t" * (@id.to_i % 3)
#STDOUT.write("\n\n#{indent}update #{@id}, role #{@role}, log length #{@persistent_state.log.count}\n\n")
case @role
when FOLLOWER_ROLE
follower_update
when CANDIDATE_ROLE
candidate_update
when LEADER_ROLE
leader_update
end
@updating = false
end
def follower_update
if @election_timer.timed_out?
#STDOUT.write("follower node #{@id} election timed out at #{Time.now.strftime('%H:%M:%S:%L')}\n")
@role = CANDIDATE_ROLE
candidate_update
end
end
protected :follower_update
def candidate_update
if @election_timer.timed_out?
#STDOUT.write("candidate node #{@id} election timed out at #{Time.now.strftime('%H:%M:%S:%L')}\n")
@persistent_state.current_term += 1
@persistent_state.voted_for = @id
reset_election_timeout
last_log_entry = @persistent_state.log.last
log_index = last_log_entry ? last_log_entry.index : nil
log_term = last_log_entry ? last_log_entry.term : nil
request = RequestVoteRequest.new(@persistent_state.current_term, @id, log_index, log_term)
votes_for = 1 # candidate always votes for self
votes_against = 0
quorum = @cluster.quorum
#STDOUT.write("\n\t\t#{@id} requests votes for term #{@persistent_state.current_term}\n\n")
@config.rpc_provider.request_votes(request, @cluster) do |voter_id, request, response|
#STDOUT.write("\n\t\t#{@id} receives vote #{response.vote_granted} from #{voter_id}\n\n")
elected = nil # no majority result yet
if request.term != @persistent_state.current_term
# this is a response to an out-of-date request, just ignore it
elsif response.term > @persistent_state.current_term
@role = FOLLOWER_ROLE
elected = false
elsif response.vote_granted
votes_for += 1
elected = true if votes_for >= quorum
else
votes_against += 1
elected = false if votes_against >= quorum
end
#STDOUT.write("\n\t\t#{@id} receives vote #{response.vote_granted}, elected is #{elected.inspect}\n\n")
elected
end
if votes_for >= quorum
#STDOUT.write("\n#{@id} becomes leader for term #{@persistent_state.current_term}\n\n")
@role = LEADER_ROLE
establish_leadership
else
#STDOUT.write("\n\t\t#{@id} not elected leader (for #{votes_for}, against #{votes_against})\n\n")
end
end
end
protected :candidate_update
def leader_update
#STDOUT.write("\nLEADER UPDATE BEGINS\n")
if @leadership_state.update_timer.timed_out?
@leadership_state.update_timer.reset!
send_heartbeats
end
if @leadership_state.followers.any?
new_commit_index = @leadership_state.followers.values.
select { |follower_state| follower_state.succeeded }.
map { |follower_state| follower_state.next_index - 1 }.
sort[@cluster.quorum - 1]
else
new_commit_index = @persistent_state.log.size - 1
end
handle_commits(new_commit_index)
#STDOUT.write("\nLEADER UPDATE ENDS\n")
end
protected :leader_update
def handle_commits(new_commit_index)
#STDOUT.write("\nnode #{@id} handle_commits(new_commit_index = #{new_commit_index}) (@temporary_state.commit_index = #{@temporary_state.commit_index}\n")
return if new_commit_index == @temporary_state.commit_index
next_commit = @temporary_state.commit_index.nil? ? 0 : @temporary_state.commit_index + 1
while next_commit <= new_commit_index
@commit_handler.call(@persistent_state.log[next_commit].command) if @commit_handler
@temporary_state.commit_index = next_commit
next_commit += 1
#STDOUT.write("\n\tnode #{@id} handle_commits(new_commit_index = #{new_commit_index}) (new @temporary_state.commit_index = #{@temporary_state.commit_index}\n")
end
end
protected :handle_commits
def establish_leadership
@leadership_state = LeadershipState.new(@config.update_interval)
@temporary_state.leader_id = @id
@cluster.node_ids.each do |node_id|
next if node_id == @id
follower_state = (@leadership_state.followers[node_id] ||= FollowerState.new)
follower_state.next_index = @persistent_state.log.size
follower_state.succeeded = false
end
send_heartbeats
end
protected :establish_leadership
def send_heartbeats
#STDOUT.write("\nnode #{@id} sending heartbeats at #{Time.now.strftime('%H:%M:%S:%L')}\n")
last_log_entry = @persistent_state.log.last
log_index = last_log_entry ? last_log_entry.index : nil
log_term = last_log_entry ? last_log_entry.term : nil
request = AppendEntriesRequest.new(
@persistent_state.current_term,
@id,
log_index,
log_term,
[],
@temporary_state.commit_index)
@config.rpc_provider.append_entries(request, @cluster) do |node_id, response|
append_entries_to_follower(node_id, request, response)
end
end
protected :send_heartbeats
def append_entries_to_follower(node_id, request, response)
if @role != LEADER_ROLE
# we lost the leadership
elsif response.success
#STDOUT.write("\nappend_entries_to_follower #{node_id} request #{request.pretty_inspect} succeeded\n")
@leadership_state.followers[node_id].next_index = (request.prev_log_index || -1) + request.entries.count + 1
@leadership_state.followers[node_id].succeeded = true
elsif response.term <= @persistent_state.current_term
#STDOUT.write("\nappend_entries_to_follower #{node_id} request failed (#{request.pretty_inspect}) and responded with #{response.pretty_inspect}\n")
@config.rpc_provider.append_entries_to_follower(request, node_id) do |node_id, response|
if @role == LEADER_ROLE # make sure leadership wasn't lost since the request
#STDOUT.write("\nappend_entries_to_follower #{node_id} callback...\n")
prev_log_index = (request.prev_log_index.nil? || request.prev_log_index <= 0) ? nil : request.prev_log_index - 1
prev_log_term = nil
entries = @persistent_state.log
unless prev_log_index.nil?
prev_log_term = @persistent_state.log[prev_log_index].term
entries = @persistent_state.log.slice((prev_log_index + 1)..-1)
end
next_request = AppendEntriesRequest.new(
@persistent_state.current_term,
@id,
prev_log_index,
prev_log_term,
entries,
@temporary_state.commit_index)
#STDOUT.write("\nappend_entries_to_follower #{node_id} request #{request.pretty_inspect} failed...\n")
#STDOUT.write("sending updated request #{next_request.pretty_inspect}\n")
@config.rpc_provider.append_entries_to_follower(next_request, node_id) do |node_id, response|
append_entries_to_follower(node_id, next_request, response)
end
end
end
end
end
protected :append_entries_to_follower
def handle_request_vote(request)
#STDOUT.write("\nnode #{@id} handling vote request from #{request.candidate_id} (request.last_log_index: #{request.last_log_index}, vs #{@persistent_state.log.last.index}\n")
response = RequestVoteResponse.new
response.term = @persistent_state.current_term
response.vote_granted = false
return response if request.term < @persistent_state.current_term
@temporary_state.leader_id = nil if request.term > @persistent_state.current_term
step_down_if_new_term(request.term)
if FOLLOWER_ROLE == @role
if @persistent_state.voted_for == request.candidate_id
response.vote_granted = true
elsif @persistent_state.voted_for.nil?
if @persistent_state.log.empty?
# this node has no log so it can't be ahead
@persistent_state.voted_for = request.candidate_id
response.vote_granted = true
elsif request.last_log_term == @persistent_state.log.last.term &&
(request.last_log_index || -1) < @persistent_state.log.last.index
# candidate's log is incomplete compared to this node
elsif (request.last_log_term || -1) < @persistent_state.log.last.term
# candidate's log is incomplete compared to this node
else
@persistent_state.voted_for = request.candidate_id
response.vote_granted = true
end
end
reset_election_timeout if response.vote_granted
end
response
end
def handle_append_entries(request)
#STDOUT.write("\n\nnode #{@id} handle_append_entries: #{request.entries.pretty_inspect}\n\n") #if request.prev_log_index.nil?
response = AppendEntriesResponse.new
response.term = @persistent_state.current_term
response.success = false
#STDOUT.write("\n\nnode #{@id} handle_append_entries for term #{request.term} (current is #{@persistent_state.current_term})\n")# if request.prev_log_index.nil?
return response if request.term < @persistent_state.current_term
#STDOUT.write("\n\nnode #{@id} handle_append_entries stage 2\n") if request.prev_log_index.nil?
step_down_if_new_term(request.term)
reset_election_timeout
@temporary_state.leader_id = request.leader_id
abs_log_index = abs_log_index_for(request.prev_log_index, request.prev_log_term)
return response if abs_log_index.nil? && !request.prev_log_index.nil? && !request.prev_log_term.nil?
#STDOUT.write("\n\nnode #{@id} handle_append_entries stage 3\n") if request.prev_log_index.nil?
if @temporary_state.commit_index &&
abs_log_index &&
abs_log_index < @temporary_state.commit_index
raise "Cannot truncate committed logs; @temporary_state.commit_index = #{@temporary_state.commit_index}; abs_log_index = #{abs_log_index}"
end
truncate_and_update_log(abs_log_index, request.entries)
return response unless update_commit_index(request.commit_index)
#STDOUT.write("\n\nnode #{@id} handle_append_entries stage 4\n") if request.prev_log_index.nil?
response.success = true
response
end
def handle_command(request)
response = CommandResponse.new(false)
case @role
when FOLLOWER_ROLE
await_leader
if @role == LEADER_ROLE
handle_command(request)
else
# forward the command to the leader
response = @config.rpc_provider.command(request, @temporary_state.leader_id)
end
when CANDIDATE_ROLE
await_leader
response = handle_command(request)
when LEADER_ROLE
last_log = @persistent_state.log.last
log_entry = LogEntry.new(@persistent_state.current_term, last_log.index ? last_log.index + 1 : 0, request.command)
@persistent_state.log << log_entry
await_consensus(log_entry)
response = CommandResponse.new(true)
end
response
end
def await_consensus(log_entry)
@config.async_provider.await do
persisted_log_entry = @persistent_state.log[log_entry.index]
!@temporary_state.commit_index.nil? &&
@temporary_state.commit_index >= log_entry.index &&
persisted_log_entry.term == log_entry.term &&
persisted_log_entry.command == log_entry.command
end
end
protected :await_consensus
def await_leader
if @temporary_state.leader_id.nil?
@role = CANDIDATE_ROLE
end
@config.async_provider.await do
@role != CANDIDATE_ROLE && !@temporary_state.leader_id.nil?
end
end
protected :await_leader
def step_down_if_new_term(request_term)
if request_term > @persistent_state.current_term
@persistent_state.current_term = request_term
@role = FOLLOWER_ROLE
end
end
protected :step_down_if_new_term
def reset_election_timeout
@election_timer.reset!
end
protected :reset_election_timeout
def abs_log_index_for(prev_log_index, prev_log_term)
@persistent_state.log.rindex { |log_entry| log_entry.index == prev_log_index && log_entry.term == prev_log_term }
end
protected :abs_log_index_for
def truncate_and_update_log(abs_log_index, entries)
log = @persistent_state.log
if abs_log_index.nil?
log = []
elsif log.length == abs_log_index + 1
# no truncation required, past log is the same
else
log = log.slice(0..abs_log_index)
end
#STDOUT.write("\n\nentries is: #{entries.pretty_inspect}\n\n")
log = log.concat(entries) unless entries.empty?
@persistent_state.log = log
end
protected :truncate_and_update_log
def update_commit_index(new_commit_index)
#STDOUT.write("\n\n%%%%%%%%%%%%%%%%%%%%% node #{@id} update_commit_index(new_commit_index = #{new_commit_index})\n")
return false if @temporary_state.commit_index && @temporary_state.commit_index > new_commit_index
handle_commits(new_commit_index)
true
end
protected :update_commit_index
end
end
| ruby | MIT | 2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c | 2026-01-04T17:54:42.497228Z | false |
harryw/raft | https://github.com/harryw/raft/blob/2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c/lib/raft/goliath.rb | lib/raft/goliath.rb | require_relative '../raft'
require 'goliath'
module Raft
class Goliath
def self.log(message)
#STDOUT.write("\n\n")
#STDOUT.write(message)
#STDOUT.write("\n\n")
end
class HttpJsonRpcResponder < ::Goliath::API
use ::Goliath::Rack::Render, 'json'
use ::Goliath::Rack::Validation::RequestMethod, %w(POST)
use ::Goliath::Rack::Params
def initialize(node)
@node = node
end
HEADERS = { 'Content-Type' => 'application/json' }
def response(env)
case env['REQUEST_PATH']
when '/request_vote'
handle_errors { request_vote_response(env['params']) }
when '/append_entries'
handle_errors { append_entries_response(env['params']) }
when '/command'
handle_errors { command_response(env['params']) }
else
error_response(404, 'not found')
end
end
def request_vote_response(params)
#STDOUT.write("\nnode #{@node.id} received request_vote from #{params['candidate_id']}, term #{params['term']}\n")
request = Raft::RequestVoteRequest.new(
params['term'],
params['candidate_id'],
params['last_log_index'],
params['last_log_term'])
response = @node.handle_request_vote(request)
[200, HEADERS, { 'term' => response.term, 'vote_granted' => response.vote_granted }]
end
def append_entries_response(params)
#STDOUT.write("\nnode #{@node.id} received append_entries from #{params['leader_id']}, term #{params['term']}\n")
entries = params['entries'].map {|entry| Raft::LogEntry.new(entry['term'], entry['index'], entry['command'])}
request = Raft::AppendEntriesRequest.new(
params['term'],
params['leader_id'],
params['prev_log_index'],
params['prev_log_term'],
entries,
params['commit_index'])
#STDOUT.write("\nnode #{@node.id} received entries: #{request.entries.pretty_inspect}\n")
response = @node.handle_append_entries(request)
#STDOUT.write("\nnode #{@node.id} completed append_entries from #{params['leader_id']}, term #{params['term']} (#{response})\n")
[200, HEADERS, { 'term' => response.term, 'success' => response.success }]
end
def command_response(params)
request = Raft::CommandRequest.new(params['command'])
response = @node.handle_command(request)
[response.success ? 200 : 409, HEADERS, { 'success' => response.success }]
end
def handle_errors
yield
rescue StandardError => se
error_response(422, se)
rescue Exception => e
error_response(500, e)
end
def error_message(exception)
"#{exception.message}\n\t#{exception.backtrace.join("\n\t")}".tap {|m| STDOUT.write("\n\n\t#{m}\n\n")}
end
def error_response(code, exception)
[code, HEADERS, { 'error' => error_message(exception) }]
end
end
module HashMarshalling
def self.hash_to_object(hash, klass)
object = klass.new
hash.each_pair do |k, v|
object.send("#{k}=", v)
end
object
end
def self.object_to_hash(object, attrs)
attrs.reduce({}) { |hash, attr|
hash[attr] = object.send(attr); hash
}
end
end
class HttpJsonRpcProvider < Raft::RpcProvider
attr_reader :uri_generator
def initialize(uri_generator)
@uri_generator = uri_generator
end
def request_votes(request, cluster, &block)
sent_hash = HashMarshalling.object_to_hash(request, %w(term candidate_id last_log_index last_log_term))
sent_json = MultiJson.dump(sent_hash)
deferred_calls = []
EM.synchrony do
cluster.node_ids.each do |node_id|
next if node_id == request.candidate_id
http = EventMachine::HttpRequest.new(uri_generator.call(node_id, 'request_vote')).apost(
:body => sent_json,
:head => { 'Content-Type' => 'application/json' })
http.callback do
if http.response_header.status == 200
received_hash = MultiJson.load(http.response)
response = HashMarshalling.hash_to_object(received_hash, Raft::RequestVoteResponse)
#STDOUT.write("\n\t#{node_id} responded #{response.vote_granted} to #{request.candidate_id}\n\n")
yield node_id, request, response
else
Raft::Goliath.log("request_vote failed for node '#{node_id}' with code #{http.response_header.status}")
end
end
deferred_calls << http
end
end
deferred_calls.each do |http|
EM::Synchrony.sync http
end
end
def append_entries(request, cluster, &block)
deferred_calls = []
EM.synchrony do
cluster.node_ids.each do |node_id|
next if node_id == request.leader_id
deferred_calls << create_append_entries_to_follower_request(request, node_id, &block)
end
end
deferred_calls.each do |http|
EM::Synchrony.sync http
end
end
def append_entries_to_follower(request, node_id, &block)
# EM.synchrony do
create_append_entries_to_follower_request(request, node_id, &block)
# end
end
def create_append_entries_to_follower_request(request, node_id, &block)
sent_hash = HashMarshalling.object_to_hash(request, %w(term leader_id prev_log_index prev_log_term entries commit_index))
sent_hash['entries'] = sent_hash['entries'].map {|obj| HashMarshalling.object_to_hash(obj, %w(term index command))}
sent_json = MultiJson.dump(sent_hash)
raise "replicating to self!" if request.leader_id == node_id
#STDOUT.write("\nleader #{request.leader_id} replicating entries to #{node_id}: #{sent_hash.pretty_inspect}\n")#"\t#{caller[0..4].join("\n\t")}")
http = EventMachine::HttpRequest.new(uri_generator.call(node_id, 'append_entries')).apost(
:body => sent_json,
:head => { 'Content-Type' => 'application/json' })
http.callback do
#STDOUT.write("\nleader #{request.leader_id} calling back to #{node_id} to append entries\n")
if http.response_header.status == 200
received_hash = MultiJson.load(http.response)
response = HashMarshalling.hash_to_object(received_hash, Raft::AppendEntriesResponse)
yield node_id, response
else
Raft::Goliath.log("append_entries failed for node '#{node_id}' with code #{http.response_header.status}")
end
end
http
end
def command(request, node_id)
sent_hash = HashMarshalling.object_to_hash(request, %w(command))
sent_json = MultiJson.dump(sent_hash)
http = EventMachine::HttpRequest.new(uri_generator.call(node_id, 'command')).apost(
:body => sent_json,
:head => { 'Content-Type' => 'application/json' })
http = EM::Synchrony.sync(http)
if http.response_header.status == 200
received_hash = MultiJson.load(http.response)
HashMarshalling.hash_to_object(received_hash, Raft::CommandResponse)
else
Raft::Goliath.log("command failed for node '#{node_id}' with code #{http.response_header.status}")
CommandResponse.new(false)
end
end
end
class EventMachineAsyncProvider < Raft::AsyncProvider
def await
f = Fiber.current
until yield
EM.next_tick {f.resume}
Fiber.yield
end
end
end
def self.rpc_provider(uri_generator)
HttpJsonRpcProvider.new(uri_generator)
end
def self.async_provider
EventMachineAsyncProvider.new
end
def initialize(node)
@node = node
end
attr_reader :node
attr_reader :update_fiber
attr_reader :running
def start(options = {})
@runner = ::Goliath::Runner.new(ARGV, nil)
@runner.api = HttpJsonRpcResponder.new(node)
@runner.app = ::Goliath::Rack::Builder.build(HttpJsonRpcResponder, @runner.api)
@runner.address = options[:address] if options[:address]
@runner.port = options[:port] if options[:port]
@runner.run
@running = true
update_proc = Proc.new do
EM.synchrony do
@node.update
end
end
@update_timer = EventMachine.add_periodic_timer(node.config.update_interval, update_proc)
# @node.update
end
def stop
@update_timer.cancel
end
end
end
| ruby | MIT | 2ffe2b10a7a548fd2d5fb1e8c3cc25af38fb776c | 2026-01-04T17:54:42.497228Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/autotest/discover.rb | autotest/discover.rb | Autotest.add_discovery { "rspec2" }
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/spec_helper.rb | spec/spec_helper.rb | require 'bundler'
Bundler.setup
require File.join(File.dirname(__FILE__), '/../lib/highrise')
Highrise::Base.user = ENV['HIGHRISE_USER'] || 'x'
Highrise::Base.oauth_token = ENV['HIGHRISE_TOKEN'] || 'TOKEN'
Highrise::Base.site = ENV['HIGHRISE_SITE'] || 'https://www.example.com'
require 'highrise/pagination_behavior'
require 'highrise/searchable_behavior'
require 'highrise/taggable_behavior'
require 'active_resource/http_mock'
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/taggable_behavior.rb | spec/highrise/taggable_behavior.rb | shared_examples_for "a taggable class" do
before(:each) do
(@tags = []).tap do
@tags << Highrise::Tag.new(:name => "cliente", :id => 414578)
@tags << Highrise::Tag.new(:name => "ged", :id => 414580)
@tags << Highrise::Tag.new(:name => "iepc", :id => 414579)
end
end
it { subject.class.included_modules.should include(Highrise::Taggable) }
it "#tag!(tag_name)" do
subject.should_receive(:post).with(:tags, :name => "client" ).and_return(true)
subject.tag!("client").should be_true
end
it "#untag!(tag_name)" do
subject.should_receive(:tags).and_return(@tags)
subject.should_receive(:delete).with("tags/414578").and_return(true)
subject.untag!("cliente").should be_true
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/group_spec.rb | spec/highrise/group_spec.rb | require 'spec_helper'
describe Highrise::Group do
it { should be_a_kind_of Highrise::Base }
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/searchable_spec.rb | spec/highrise/searchable_spec.rb | require 'spec_helper'
describe Highrise::Searchable do
class TestClass < Highrise::Base; include Highrise::Searchable; end
subject { TestClass.new }
it_should_behave_like "a searchable class"
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/task_category_spec.rb | spec/highrise/task_category_spec.rb | require 'spec_helper'
describe Highrise::TaskCategory do
subject { Highrise::TaskCategory.new(:id => 1, :name => "Task Category") }
it { should be_a_kind_of Highrise::Base }
it ".find_by_name" do
task_category = Highrise::TaskCategory.new(:id => 2, :name => "Another Task Category")
Highrise::TaskCategory.should_receive(:find).with(:all).and_return([task_category, subject])
Highrise::TaskCategory.find_by_name("Task Category").should == subject
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/searchable_behavior.rb | spec/highrise/searchable_behavior.rb | shared_examples_for "a searchable class" do
it { subject.class.included_modules.should include(Highrise::Searchable) }
it ".search" do
find_args = {:from => "/#{subject.class.collection_name}/search.xml", :params => {"criteria[email]" => "john.doe@example.com", "criteria[zip]" => "90210"}}
if subject.class.respond_to?(:find_all_across_pages)
subject.class.should_receive(:find_all_across_pages).with(find_args)
else
subject.class.should_receive(:find).with(:all, find_args)
end
subject.class.search(:email => "john.doe@example.com", :zip => "90210")
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/email_spec.rb | spec/highrise/email_spec.rb | require 'spec_helper'
describe Highrise::Email do
it { should be_a_kind_of Highrise::Base }
it_should_behave_like "a paginated class"
it "#comments" do
subject.should_receive(:id).and_return(1)
Highrise::Comment.should_receive(:find).with(:all, {:from=>"/emails/1/comments.xml"}).and_return("comments")
subject.comments.should == "comments"
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/pagination_behavior.rb | spec/highrise/pagination_behavior.rb | shared_examples_for "a paginated class" do
it { subject.class.included_modules.should include(Highrise::Pagination) }
it ".find_all_across_pages" do
subject.class.should_receive(:find).with(:all,{:params=>{:n=>0}}).and_return(["things"])
subject.class.should_receive(:find).with(:all,{:params=>{:n=>1}}).and_return([])
subject.class.find_all_across_pages.should == ["things"]
end
it ".find_all_across_pages with zero results" do
subject.class.should_receive(:find).with(:all,{:params=>{:n=>0}}).and_return(nil)
subject.class.find_all_across_pages.should == []
end
it ".find_all_across_pages_since" do
time = Time.parse("Wed Jan 14 15:43:11 -0200 2009")
subject.class.should_receive(:find_all_across_pages).with({:params=>{:since=>"20090114174311"}}).and_return("result")
subject.class.find_all_across_pages_since(time).should == "result"
end
it ".find_all_deletions_across_pages" do
class TestClass2 < Highrise::Base; include Highrise::Pagination; end
subject_type = subject.class.to_s.split('::').last
deleted_resource_1 = subject.class.new(:id => 12, :type => subject_type)
deleted_resource_2 = TestClass2.new(:id => 34, :type => 'TestClass2')
deleted_resource_3 = subject.class.new(:id => 45, :type => subject_type)
subject.class.should_receive(:find).with(:all,{:from => '/deletions.xml', :params=>{:n=>1}}).and_return([deleted_resource_1, deleted_resource_2, deleted_resource_3])
subject.class.should_receive(:find).with(:all,{:from => '/deletions.xml', :params=>{:n=>2}}).and_return([])
subject.class.find_all_deletions_across_pages.should == [deleted_resource_1, deleted_resource_3]
end
it ".find_all_deletions_across_pages with zero results" do
subject.class.should_receive(:find).with(:all,{:from => '/deletions.xml', :params=>{:n=>1}}).and_return(nil)
subject.class.find_all_deletions_across_pages.should == []
end
it ".find_all_deletions_across_pages_since" do
class TestClass2 < Highrise::Base; include Highrise::Pagination; end
subject_type = subject.class.to_s.split('::').last
time = Time.parse("Wed Jan 14 15:43:11 -0200 2009")
deleted_resource_1 = subject.class.new(:id => 12, :type => subject_type)
deleted_resource_2 = TestClass2.new(:id => 34, :type => 'TestClass2')
deleted_resource_3 = subject.class.new(:id => 45, :type => subject_type)
subject.class.should_receive(:find).with(:all,{:from => '/deletions.xml', :params=>{:n=>1, :since=>"20090114174311"}}).and_return([deleted_resource_1, deleted_resource_2, deleted_resource_3])
subject.class.should_receive(:find).with(:all,{:from => '/deletions.xml', :params=>{:n=>2, :since=>"20090114174311"}}).and_return([])
subject.class.find_all_deletions_across_pages_since(time).should == [deleted_resource_1, deleted_resource_3]
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/membership_spec.rb | spec/highrise/membership_spec.rb | require 'spec_helper'
describe Highrise::Membership do
it { should be_a_kind_of Highrise::Base }
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/deal_spec.rb | spec/highrise/deal_spec.rb | require 'spec_helper'
describe Highrise::Deal do
subject { Highrise::Deal.new(:id => 1) }
it { should be_a_kind_of Highrise::Subject }
it ".add_note" do
Highrise::Note.should_receive(:create).with({:body=>"body", :subject_id=>1, :subject_type=>'Deal'}).and_return(mock('note'))
subject.add_note :body=>'body'
end
describe ".update_status" do
it { expect { subject.update_status("invalid") }.to raise_error(ArgumentError) }
%w[pending won lost].each do |status|
it "updates status to #{status}" do
subject.should_receive(:put).with(:status, :status => {:name => status})
subject.update_status(status)
end
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/party_spec.rb | spec/highrise/party_spec.rb | require 'spec_helper'
describe Highrise::Party do
it { should be_a_kind_of Highrise::Base }
it ".recently_viewed" do
Highrise::Party.should_receive(:find).with(:all, {:from => '/parties/recently_viewed.xml'})
Highrise::Party.recently_viewed
end
it ".deletions_since" do
time = Time.parse("Wed Jan 14 15:43:11 -0200 2009")
Highrise::Party.should_receive(:find).with(:all, {:from => '/parties/deletions.xml', :params=>{:since=>"20090114174311"}}).and_return("result")
Highrise::Party.deletions_since(time).should == "result"
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/recording_spec.rb | spec/highrise/recording_spec.rb | require 'spec_helper'
describe Highrise::Recording do
it { should be_a_kind_of Highrise::Base }
it_should_behave_like "a paginated class"
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/pagination_spec.rb | spec/highrise/pagination_spec.rb | require 'spec_helper'
describe Highrise::Pagination do
class TestClass < Highrise::Base; include Highrise::Pagination; end
subject { TestClass.new }
it_should_behave_like "a paginated class"
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/task_spec.rb | spec/highrise/task_spec.rb | require 'spec_helper'
describe Highrise::Task do
it { should be_a_kind_of Highrise::Base }
it "#complete!" do
subject.should_receive(:load_attributes_from_response).with("post")
subject.should_receive(:post).with(:complete).and_return("post")
subject.complete!
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/person_spec.rb | spec/highrise/person_spec.rb | # encoding: utf-8
require 'spec_helper'
describe Highrise::Person do
subject { Highrise::Person.new(:id => 1) }
it { should be_a_kind_of Highrise::Subject }
it_should_behave_like "a paginated class"
it_should_behave_like "a taggable class"
it_should_behave_like "a searchable class"
describe "#company" do
it "returns nil when it doesn't have a company" do
subject.should_receive(:company_id).and_return(nil)
subject.company.should be_nil
end
it "delegate to Highrise::Company when have company_id" do
subject.should_receive(:company_id).at_least(2).times.and_return(1)
Highrise::Company.should_receive(:find).with(1).and_return("company")
subject.company.should == "company"
end
end
it "#name" do
subject.should_receive(:first_name).and_return("Marcos")
subject.should_receive(:last_name).and_return("Tapajós ")
subject.name.should == "Marcos Tapajós"
end
describe "#email_addresses" do
it "returns an empty array when there are none set" do
subject.email_addresses.should == []
end
it "returns all email_addresses as string in an array" do
subject = Highrise::Person.new(:id => 1,
:contact_data => {
:email_addresses => [{
:email_address => {
:address => "important@person.com"
}
}]
})
subject.email_addresses.should == ["important@person.com"]
end
end
describe "#phone_numbers" do
it "returns an empty array when there is none set" do
subject.phone_numbers.should== []
end
it "returns all phone numbers as a string aray" do
subject = Highrise::Person.new(:id => 1,
:contact_data => {
:phone_numbers => [{
:phone_number => {
:number => "123456789"
}
}]
})
subject.phone_numbers.should== [ "123456789" ]
end
end
describe "#tags" do
let(:person_tags) { [
{'id' => "414578", 'name' => "cliente"},
{'id' => "414580", 'name' => "ged"},
{'id' => "414579", 'name' => "iepc"} ]
}
let(:person_john_doe) { { :id => 1, :first_name => "John", :last_name => "Doe" } }
let(:person_john_doe_request){ ActiveResource::Request.new(:get, '/people/1.xml', nil, {"Authorization"=>"Bearer OAUTH_TOKEN", "Accept"=>"application/xml"}) }
let(:person_john_doe_request_pair){ {person_john_doe_request => ActiveResource::Response.new(person_john_doe.to_xml, 200, {})} }
it "should return the tags as a Highrise::Tag" do
person_john_doe[:tags] = person_tags
ActiveResource::HttpMock.respond_to(person_john_doe_request_pair)
tags = person_tags.collect {|tag| Highrise::Tag.new(tag)}
subject.tags.should == tags
end
it "should return an empty collection when there are no tags" do
ActiveResource::HttpMock.respond_to(person_john_doe_request_pair)
subject.tags.should == []
end
end
describe "#tags" do
before(:each) do
(@tags = []).tap do
@tags << {'id' => "414578", 'name' => "cliente"}
@tags << {'id' => "414580", 'name' => "ged"}
@tags << {'id' => "414579", 'name' => "iepc"}
end
subject.attributes["tags"] = @tags
end
it {
subject.tags.should == @tags
}
end
describe "Custom fields" do
before (:each) do
@fruit_person = Highrise::Person.new({ :person => {
:id => 1,
:first_name => "John",
:last_name => "Doe",
:subject_datas => [{
:subject_field_label => "Fruit Banana",
:value => "Yellow"
}, {
:subject_field_label => "Fruit Grape",
:value => "Green"
}]
}
})
@subject_field_blueberry = Highrise::SubjectField.new ({:id => 1, :label => "Fruit Blueberry"})
@subject_field_papaya = Highrise::SubjectField.new ({:id => 2, :label => "Fruit Papaya"})
end
it "Can get the value of a custom field via the field method" do
@fruit_person.field("Fruit Banana").should== "Yellow"
end
it "Can get the value of a custom field using a custom method call" do
@fruit_person.fruit_grape.should== "Green"
end
it "Will raise an exception on an unknown field" do
expect {@fruit_person.unknown_fruit}.to raise_exception(NoMethodError)
end
it "Can set the value of a custom field via the field method" do
@fruit_person.set_field_value("Fruit Grape", "Red")
@fruit_person.field("Fruit Grape").should== "Red"
end
it "Can set the value of a custom field" do
@fruit_person.fruit_grape= "Red"
@fruit_person.fruit_grape.should== "Red"
end
it "Assignment just returns the arguments (like ActiveResource base does)" do
Highrise::SubjectField.should_receive(:find).with(:all).and_return []
(@fruit_person.unknown_fruit = 10).should== 10
end
it "Can deal with the find returning nil (which is a bit ugly in the ActiveResource API)" do
Highrise::SubjectField.should_receive(:find).with(:all).and_return nil
(@fruit_person.unknown_fruit = 10).should== 10
end
it "Can set the value of a custom field that wasn't there via the field method, but that was defined (happens on new Person)" do
Highrise::SubjectField.should_receive(:find).with(:all).and_return([@subject_field_papaya, @subject_field_blueberry])
@fruit_person.set_field_value("Fruit Blueberry", "Purple")
@fruit_person.field("Fruit Blueberry").should== "Purple"
@fruit_person.attributes["subject_datas"][2].subject_field_id.should == 1
end
it "Can still set and read the usual way of reading attrivutes" do
@fruit_person.first_name = "Jacob"
@fruit_person.first_name.should== "Jacob"
end
end
it { subject.label.should == 'Party' }
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/company_spec.rb | spec/highrise/company_spec.rb | require 'spec_helper'
describe Highrise::Company do
subject { Highrise::Company.new(:id => 1) }
it { should be_a_kind_of Highrise::Base }
it_should_behave_like "a paginated class"
it_should_behave_like "a taggable class"
it_should_behave_like "a searchable class"
it "#people" do
Highrise::Person.should_receive(:find_all_across_pages).with(:from=>"/companies/1/people.xml").and_return("people")
subject.people.should == "people"
end
describe "Custom fields" do
before (:each) do
@fruit_company = Highrise::Company.new({ :company => {
:id => 1,
:name => "John Doe & Co.",
:subject_datas => [{
:subject_field_label => "Fruit Banana",
:value => "Yellow"
}, {
:subject_field_label => "Fruit Grape",
:value => "Green"
}]
}
})
@subject_field_blueberry = Highrise::SubjectField.new ({:id => 1, :label => "Fruit Blueberry"})
@subject_field_papaya = Highrise::SubjectField.new ({:id => 2, :label => "Fruit Papaya"})
end
it "Can get the value of a custom field via the field method" do
@fruit_company.field("Fruit Banana").should== "Yellow"
end
it "Can get the value of a custom field using a custom method call" do
@fruit_company.fruit_grape.should== "Green"
end
it "Will raise an exception on an unknown field" do
expect {@fruit_company.unknown_fruit}.to raise_exception(NoMethodError)
end
it "Can set the value of a custom field via the field method" do
@fruit_company.set_field_value("Fruit Grape", "Red")
@fruit_company.field("Fruit Grape").should== "Red"
end
it "Can set the value of a custom field" do
@fruit_company.fruit_grape= "Red"
@fruit_company.field("Fruit Grape").should== "Red"
end
it "Assignment just returns the arguments (like ActiveResource base does)" do
Highrise::SubjectField.should_receive(:find).with(:all).and_return []
(@fruit_company.unknown_fruit = 10).should== 10
end
it "Can deal with the find returning nil (which is a bit ugly in the ActiveResource API)" do
Highrise::SubjectField.should_receive(:find).with(:all).and_return nil
(@fruit_company.unknown_fruit = 10).should== 10
end
it "Can set the value of a custom field that wasn't there via the field method, but that was defined (happens on new Person)" do
Highrise::SubjectField.should_receive(:find).with(:all).and_return([@subject_field_papaya, @subject_field_blueberry])
@fruit_company.set_field_value("Fruit Blueberry", "Purple")
@fruit_company.field("Fruit Blueberry").should== "Purple"
@fruit_company.attributes["subject_datas"][2].subject_field_id.should == 1
end
it "Can still set and read the usual way of reading attrivutes" do
@fruit_company.name = "Jacob"
@fruit_company.name.should== "Jacob"
end
end
it { subject.label.should == 'Party' }
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/base_spec.rb | spec/highrise/base_spec.rb | require 'spec_helper'
describe Highrise::Base do
it { subject.should be_a_kind_of ActiveResource::Base }
describe "dynamic finder methods" do
context "without pagination" do
before do
@deal_one = Highrise::Base.new(:id => 1, :name => "A deal")
@deal_two = Highrise::Base.new(:id => 2, :name => "A deal")
@deal_three = Highrise::Base.new(:id => 3, :name => "Another deal")
Highrise::Base.should_receive(:find).with(:all).and_return([@deal_one, @deal_two, @deal_three])
end
it ".find_by_(attribute) finds one" do
Highrise::Base.find_by_name("A deal").should == @deal_one
end
it ".find_all_by_(attribute) finds all" do
Highrise::Base.find_all_by_name("A deal").should == [@deal_one, @deal_two]
end
end
context "with pagination" do
before do
class PaginatedBaseClass < Highrise::Base; include Highrise::Pagination; end
@john_doe = PaginatedBaseClass.new(:id => 1, :first_name => "John")
@john_baker = PaginatedBaseClass.new(:id => 2, :first_name => "John")
@joe_smith = PaginatedBaseClass.new(:id => 3, :first_name => "Joe")
PaginatedBaseClass.should_receive(:find_all_across_pages).and_return([@john_doe, @john_baker, @joe_smith])
end
it ".find_by_(attribute) finds one" do
PaginatedBaseClass.find_by_first_name("John").should == @john_doe
end
it ".find_all_by_(attribute) finds all" do
PaginatedBaseClass.find_all_by_first_name("John").should == [@john_doe, @john_baker]
end
end
it "expects arguments to the finder" do
expect { Highrise::Base.find_all_by_first_name }.to raise_error(ArgumentError)
end
it "falls back to regular method missing" do
expect { Highrise::Base.any_other_method }.to raise_error(NoMethodError)
end
end
describe "when using an oauth token" do
it ".oauth_token= writes a bearer authorization header" do
Highrise::Base.oauth_token = 'OAUTH_TOKEN'
Highrise::Base.headers['Authorization'].should == 'Bearer OAUTH_TOKEN'
end
end
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/tag_spec.rb | spec/highrise/tag_spec.rb | require 'spec_helper'
describe Highrise::Tag do
subject { Highrise::Tag.new(:id => 1, :name => "Name") }
it { should be_a_kind_of Highrise::Base }
it "supports equality" do
tag = Highrise::Tag.new(:id => 1, :name => "Name")
subject.should == tag
end
it ".find_by_name" do
tag = Highrise::Tag.new(:id => 2, :name => "Next")
Highrise::Tag.should_receive(:find).with(:all).and_return([tag, subject])
Highrise::Tag.find_by_name("Name").should == subject
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/taggable_spec.rb | spec/highrise/taggable_spec.rb | require 'spec_helper'
describe Highrise::Taggable do
class TestClass < Highrise::Base; include Highrise::Taggable; end
subject { TestClass.new }
it_should_behave_like "a taggable class"
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/kase_spec.rb | spec/highrise/kase_spec.rb | require 'spec_helper'
describe Highrise::Kase do
it { should be_a_kind_of Highrise::Subject }
it_should_behave_like "a paginated class"
it "#close!" do
mocked_now = Time.parse("Wed Jan 14 15:43:11 -0200 2009")
Time.should_receive(:now).and_return(mocked_now)
subject.should_receive(:update_attribute).with(:closed_at, mocked_now.utc)
subject.close!
end
it "#open!" do
subject.should_receive(:update_attribute).with(:closed_at, nil)
subject.open!
end
it ".all_open_across_pages" do
subject.class.should_receive(:find).with(:all,{:from=>"/kases/open.xml",:params=>{:n=>0}}).and_return(["things"])
subject.class.should_receive(:find).with(:all,{:from=>"/kases/open.xml",:params=>{:n=>1}}).and_return([])
subject.class.all_open_across_pages.should == ["things"]
end
it ".all_closed_across_pages" do
subject.class.should_receive(:find).with(:all,{:from=>"/kases/closed.xml",:params=>{:n=>0}}).and_return(["things"])
subject.class.should_receive(:find).with(:all,{:from=>"/kases/closed.xml",:params=>{:n=>1}}).and_return([])
subject.class.all_closed_across_pages.should == ["things"]
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/subject_spec.rb | spec/highrise/subject_spec.rb | require 'spec_helper'
describe Highrise::Subject do
subject { Highrise::Subject.new(:id => 1) }
it { should be_a_kind_of Highrise::Base }
it "#notes" do
Highrise::Note.should_receive(:find_all_across_pages).with({:from=>"/subjects/1/notes.xml"}).and_return("notes")
subject.notes.should == "notes"
end
it "#add_note" do
Highrise::Note.should_receive(:create).with({:body=>"body", :subject_id=>1, :subject_type=>'Subject'}).and_return(mock('note'))
subject.add_note :body=>'body'
end
it "#add_task" do
Highrise::Task.should_receive(:create).with({:body=>"body", :subject_id=>1, :subject_type=>'Subject'}).and_return(mock('task'))
subject.add_task :body=>'body'
end
it "#emails" do
Highrise::Email.should_receive(:find_all_across_pages).with({:from=>"/subjects/1/emails.xml"}).and_return("emails")
subject.emails.should == "emails"
end
it "#upcoming_tasks" do
Highrise::Task.should_receive(:find).with(:all, {:from=>"/subjects/1/tasks.xml"}).and_return("tasks")
subject.upcoming_tasks.should == "tasks"
end
context 'finding with since param' do
before(:each) do
@utc_time_str = "20090114174311"
end
it "#notes" do
Highrise::Note.should_receive(:find_all_across_pages).with({:from=>"/subjects/1/notes.xml", :params=>{:since=>@utc_time_str}}).and_return("notes")
subject.notes(:params=>{:since=>@utc_time_str}).should == "notes"
end
it "#emails" do
Highrise::Email.should_receive(:find_all_across_pages).with({:from=>"/subjects/1/emails.xml", :params=>{:since=>@utc_time_str}}).and_return("emails")
subject.emails(:params=>{:since=>@utc_time_str}).should == "emails"
end
it "#tasks" do
Highrise::Task.should_receive(:find).with(:all, {:from=>"/subjects/1/tasks.xml", :params=>{:since=>@utc_time_str}}).and_return("tasks")
subject.upcoming_tasks(:params=>{:since=>@utc_time_str}).should == "tasks"
end
end
it { subject.label.should == "Subject" }
end | ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/account_spec.rb | spec/highrise/account_spec.rb | require 'spec_helper'
describe Highrise::Account do
it { should be_a_kind_of Highrise::Base }
it ".me" do
Highrise::Account.should_receive(:find).with(:one, {:from => "/account.xml"}).and_return(subject)
Highrise::Account.me.should == subject
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/subject_field_spec.rb | spec/highrise/subject_field_spec.rb | require 'spec_helper'
describe Highrise::SubjectField do
it { should be_a_kind_of Highrise::Base }
let(:two_subject_fields){ [
Highrise::SubjectField.new({:id => 1, :label => "Cabbage"}),
Highrise::SubjectField.new({:id => 2, :label => "Chicken"})]
}
let(:four_subject_fields){ [
two_subject_fields,
Highrise::SubjectField.new({:id => 3, :label => "Pasta"}),
Highrise::SubjectField.new({:id => 4, :label => "Beans"})].flatten
}
let(:subject_field_request){ ActiveResource::Request.new(:get, '/subject_fields.xml', nil, {"Authorization"=>"Bearer OAUTH_TOKEN", "Accept"=>"application/xml"}) }
let(:two_subject_fields_request_pair){ {subject_field_request => ActiveResource::Response.new(two_subject_fields.to_xml, 200, {})} }
let(:four_subject_fields_request_pair){ { subject_field_request => ActiveResource::Response.new(four_subject_fields.to_xml, 200, {})} }
context 'cache disabled (default)' do
it "does not use cache for queries" do
ActiveResource::HttpMock.respond_to(two_subject_fields_request_pair)
Highrise::SubjectField.find(:all)
ActiveResource::HttpMock.respond_to(four_subject_fields_request_pair)
Highrise::SubjectField.find(:all).size.should== 4
end
end
context 'cache enabled (opt-in)' do
before(:each) do
Highrise::SubjectField.use_cache(true)
end
it "caches 'find all' to prevent too much queries for the SubjectFields" do
ActiveResource::HttpMock.respond_to(two_subject_fields_request_pair)
Highrise::SubjectField.find(:all)
ActiveResource::HttpMock.reset!
Highrise::SubjectField.find(:all).size.should== 2
end
it "invalidates cache" do
ActiveResource::HttpMock.respond_to(two_subject_fields_request_pair)
Highrise::SubjectField.find(:all)
Highrise::SubjectField.invalidate_cache
ActiveResource::HttpMock.respond_to(four_subject_fields_request_pair)
Highrise::SubjectField.find(:all).size.should== 4
end
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
tapajos/highrise | https://github.com/tapajos/highrise/blob/1a1d4a2ea38dce8aa7ade974604f81d829d9c359/spec/highrise/deal_category_spec.rb | spec/highrise/deal_category_spec.rb | require 'spec_helper'
describe Highrise::DealCategory do
subject { Highrise::DealCategory.new(:id => 1, :name => "Deal Category") }
it { should be_a_kind_of Highrise::Base }
it ".find_by_name" do
deal_category = Highrise::DealCategory.new(:id => 2, :name => "Another Deal Category")
Highrise::DealCategory.should_receive(:find).with(:all).and_return([deal_category, subject])
Highrise::DealCategory.find_by_name("Deal Category").should == subject
end
end
| ruby | MIT | 1a1d4a2ea38dce8aa7ade974604f81d829d9c359 | 2026-01-04T17:54:47.038387Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.