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 |
|---|---|---|---|---|---|---|---|---|
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/new_rails_defaults.rb | config/initializers/new_rails_defaults.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
if defined?(ActiveRecord)
# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true
# Store the full class name (including module namespace) in STI type column.
ActiveRecord::Base.store_full_sti_class = true
end
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/factory_girl.rb | config/initializers/factory_girl.rb | # frozen_string_literal: true
require 'active_support/testing/time_helpers'
if defined? FactoryGirl
FactoryGirl::SyntaxRunner.send(:include, ActiveSupport::Testing::TimeHelpers)
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/wrap_parameters.rb | config/initializers/wrap_parameters.rb | # frozen_string_literal: true
# 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] if respond_to?(:wrap_parameters)
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/inflections.rb | config/initializers/inflections.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/simple_form_bootstrap.rb | config/initializers/simple_form_bootstrap.rb | # frozen_string_literal: true
require 'simple_form_extensions'
# Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config|
config.error_notification_class = 'alert alert-danger'
config.button_class = 'btn btn-default'
config.boolean_label_class = nil
config.wrappers :vertical_form,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'control-label'
b.use :input, class: 'form-control'
b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
config.wrappers :vertical_file_input,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :readonly
b.use :label, class: 'control-label'
b.use :input
b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
config.wrappers :vertical_boolean,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.optional :readonly
b.wrapper tag: 'div', class: 'checkbox' do |ba|
ba.use :label_input
end
b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
config.wrappers :vertical_radio_and_checkboxes,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'control-label'
b.use :input
b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
config.wrappers :horizontal_form,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'col-sm-2 control-label'
b.wrapper tag: 'div', class: 'col-sm-7' do |ba|
ba.use :input, class: 'form-control'
ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
config.wrappers :horizontal_file_input,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :readonly
b.use :label, class: 'col-sm-2 control-label'
b.wrapper tag: 'div', class: 'col-sm-7' do |ba|
ba.use :input
ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
config.wrappers :horizontal_select2,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :readonly
b.use :label, class: 'col-sm-2 control-label'
b.wrapper tag: 'div', class: 'col-sm-7' do |ba|
ba.use :input
ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
config.wrappers :horizontal_boolean,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.optional :readonly
b.wrapper tag: 'div', class: 'col-sm-offset-2 col-sm-7' do |wr|
wr.wrapper tag: 'div', class: 'checkbox' do |ba|
ba.use :label_input
end
wr.use :error, wrap_with: { tag: 'span', class: 'help-block' }
wr.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
config.wrappers :horizontal_radio_and_checkboxes,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.optional :readonly
b.use :label, class: 'col-sm-2 control-label'
b.wrapper tag: 'div', class: 'col-sm-7' do |ba|
ba.use :input
ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
config.wrappers :inline_form,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'sr-only'
b.use :input, class: 'form-control'
b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
config.wrappers :vertical_input_group,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.use :label, class: 'control-label'
b.wrapper tag: 'div' do |ba|
ba.wrapper tag: 'div', class: 'input-group col-sm-12' do |append|
append.use :input, class: 'form-control'
end
ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
config.wrappers :horizontal_input_group,
tag: 'div',
class: 'form-group',
error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.use :label, class: 'col-sm-2 control-label'
b.wrapper tag: 'div', class: 'col-sm-7' do |ba|
ba.wrapper tag: 'div', class: 'input-group col-sm-12' do |append|
append.use :input, class: 'form-control'
end
ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
end
end
# Wrappers for forms and inputs using the Bootstrap toolkit.
# Check the Bootstrap docs (http://getbootstrap.com)
# to learn about the different styles for forms and inputs,
# buttons and other elements.
config.default_wrapper = :horizontal_form
config.wrapper_mappings = {
check_boxes: :horizontal_radio_and_checkboxes,
radio_buttons: :horizontal_radio_and_checkboxes,
file: :horizontal_file_input,
boolean: :horizontal_boolean
}
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/kaminari_config.rb | config/initializers/kaminari_config.rb | # frozen_string_literal: true
Kaminari.configure do |config|
# config.default_per_page = 25
config.window = 2
# config.outer_window = 0
# config.left = 0
# config.right = 0
# config.page_method_name = :page
# config.param_name = :page
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/rails_admin.rb | config/initializers/rails_admin.rb | # frozen_string_literal: true
RailsAdmin.config do |config|
### Popular gems integration
# inherit from application controller
config.parent_controller = 'ApplicationController'
## == Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
## == Cancan ==
config.authorize_with :cancancan
## == PaperTrail ==
# PaperTrail >= 3.0.0
# config.audit_with :paper_trail, 'User', 'PaperTrail::Version'
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
config.actions do
dashboard # mandatory
index # mandatory
new
export
bulk_delete
show
edit
# delete
show_in_app
# modified delete method to deal with objects with soft deletion
member :force_delete, :delete do
i18n_key :delete
controller do
proc do
if request.get? # DELETE
respond_to do |format|
format.html { render @action.template_name }
format.js { render @action.template_name, layout: false }
end
elsif request.delete? # DESTROY
# optionally pass the force parameter
opt = :force if @object.has_attribute?(:deleted_at)
redirect_path = nil
@auditing_adapter &&
@auditing_adapter.delete_object(@object, @abstract_model,
_current_user)
if @object.send(:destroy, opt)
flash[:success] = t('admin.flash.successful',
name: @model_config.label,
action: t('admin.actions.delete.done'))
redirect_path = index_path
else
flash[:error] = t('admin.flash.error',
name: @model_config.label,
action: t('admin.actions.delete.done'))
redirect_path = back_or_index
end
redirect_to redirect_path
end
end
end
end
## With an audit adapter, you can add:
# history_index
# history_show
end
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/setup_mail.rb | config/initializers/setup_mail.rb | # frozen_string_literal: true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
address: Rails.application.secrets.smtp_address,
port: Rails.application.secrets.smtp_port,
domain: Rails.application.secrets.smtp_domain,
enable_starttls_auto: true
}
# optional server authentication
if ENV['RES_SMTP_AUTH']
ActionMailer::Base.smtp_settings[:authentication] = :login
ActionMailer::Base.smtp_settings[:user_name] =
Rails.application.secrets.smtp_username
ActionMailer::Base.smtp_settings[:password] =
Rails.application.secrets.smtp_password
end
# logging of automatically sent emails
class MailObserver
def self.delivered_email(message)
if ENV['LOG_EMAILS']
Rails.logger.info "Sent #{message.subject} to #{message.to}"
end
end
end
ActionMailer::Base.register_observer(MailObserver)
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/simple_form.rb | config/initializers/simple_form.rb | # frozen_string_literal: true
# Use this setup block to configure all options available in SimpleForm.
# rubocop:disable Metrics/LineLength
SimpleForm.setup do |config|
# Wrappers are used by the form builder to generate a
# complete input. You can remove any component from the
# wrapper, change the order or even add your own to the
# stack. The options given below are used to wrap the
# whole input.
config.wrappers :default,
class: :input,
hint_class: :field_with_hint,
error_class: :field_with_errors do |b|
## Extensions enabled by default
# Any of these extensions can be disabled for a
# given input by passing: `f.input EXTENSION_NAME => false`.
# You can make any of these extensions optional by
# renaming `b.use` to `b.optional`.
# Determines whether to use HTML5 (:email, :url, ...)
# and required attributes
b.use :html5
# Calculates placeholders automatically from I18n
# You can also pass a string as f.input placeholder: "Placeholder"
b.use :placeholder
## Optional extensions
# They are disabled unless you pass `f.input EXTENSION_NAME => true`
# to the input. If so, they will retrieve the values from the model
# if any exists. If you want to enable any of those
# extensions by default, you can change `b.optional` to `b.use`.
# Calculates maxlength from length validations for string inputs
b.optional :maxlength
# Calculates pattern from format validations for string inputs
b.optional :pattern
# Calculates min and max from length validations for numeric inputs
b.optional :min_max
# Calculates readonly automatically from readonly attributes
b.optional :readonly
## Inputs
b.use :label_input
b.use :hint, wrap_with: { tag: :span, class: :hint }
b.use :error, wrap_with: { tag: :span, class: :error }
## full_messages_for
# If you want to display the full error message for the attribute, you can
# use the component :full_error, like:
#
# b.use :full_error, wrap_with: { tag: :span, class: :error }
end
# The default wrapper to be used by the FormBuilder.
config.default_wrapper = :default
# Define the way to render check boxes / radio buttons with labels.
# Defaults to :nested for bootstrap config.
# inline: input + label
# nested: label > input
config.boolean_style = :nested
# Default class for buttons
config.button_class = 'btn btn-default'
# Method used to tidy up errors. Specify any Rails Array method.
# :first lists the first message for each field.
# Use :to_sentence to list all errors for each field.
# config.error_method = :first
# Default tag used for error notification helper.
config.error_notification_tag = :div
# CSS class to add for error notification helper.
config.error_notification_class = 'error_notification'
# ID to add for error notification helper.
# config.error_notification_id = nil
# Series of attempts to detect a default label method for collection.
# config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attempts to detect a default value method for collection.
# config.collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag,
# defaulting to none.
# config.collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to
# none.
# config.collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag,
# defaulting to :span. Please note that when using :boolean_style = :nested,
# SimpleForm will force this option to be a label.
# config.item_wrapper_tag = :span
# You can define a class to use in all item wrappers. Defaulting to none.
# config.item_wrapper_class = nil
# How the label text should be generated altogether with the required text.
# config.label_text = lambda { |label, required, explicit_label| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
# config.label_class = nil
# You can define the default class to be used on forms. Can be overriden
# with `html: { :class }`. Defaulting to none.
# config.default_form_class = nil
# You can define which elements should obtain additional classes
# config.generate_additional_classes_for = [:wrapper, :label, :input]
# Whether attributes are required by default (or not). Default is true.
# config.required_by_default = true
# Tell browsers whether to use the native HTML5 validations (novalidate form option).
# These validations are enabled in SimpleForm's internal config but disabled by default
# in this configuration, which is recommended due to some quirks from different browsers.
# To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations,
# change this configuration to true.
config.browser_validations = false
# Collection of methods to detect if a file type was given.
# config.file_methods = [ :mounted_as, :file?, :public_filename ]
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value.
# config.input_mappings = { /count/ => :integer }
# Custom wrappers for input types. This should be a hash containing an input
# type as key and the wrapper that will be used for all inputs with specified type.
# config.wrapper_mappings = { string: :prepend }
# Namespaces where SimpleForm should look for custom input classes that
# override default inputs.
# config.custom_inputs_namespaces << "CustomInputs"
# Default priority for time_zone inputs.
# config.time_zone_priority = nil
# Default priority for country inputs.
# config.country_priority = nil
# When false, do not use translations for labels.
# config.translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
# config.inputs_discovery = true
# Cache SimpleForm inputs discovery
# config.cache_discovery = !Rails.env.development?
# Default class for inputs
# config.input_class = nil
# Define the default class of the input wrapper of the boolean input.
config.boolean_label_class = 'checkbox'
# Defines if the default input wrapper class should be included in radio
# collection wrappers.
# config.include_default_input_wrapper_class = true
# Defines which i18n scope will be used in Simple Form.
# config.i18n_scope = 'simple_form'
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/cookies_serializer.rb | config/initializers/cookies_serializer.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :marshal
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/00_devise.rb | config/initializers/00_devise.rb | # frozen_string_literal: true
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = Rails.application.secrets.devise_secret_key
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer = 'DeviseMailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
if ENV['CAS_AUTH'].blank?
# For bcrypt, this is the cost for hashing the password and defaults to 10.
# If using other encryptors, it sets how many times you want the password
# re-encrypted.
#
# Limiting the stretches to just one in testing will increase the
# performance of your test suite dramatically. However, it is STRONGLY
# RECOMMENDED to not use a value less than 10 in other environments. Note
# that, for bcrypt (the default encryptor), the cost increases
# exponentially with the number of stretches (e.g. a value of 20 is
# already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
config.pepper = Rails.application.secrets.devise_pepper
# ==> Configuration for :recoverable
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials
# again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
end
# ==> devise_cas_authenticatable configuration
if ENV['CAS_AUTH'].present?
# configure the base URL of your CAS server
config.cas_base_url = Rails.application.secrets.cas_base_url
# you can override these if you need to, but cas_base_url is usually
# enough
# config.cas_login_url = "https://cas.myorganization.com/login"
# config.cas_logout_url = "https://cas.myorganization.com/logout"
# config.cas_validate_url = "https://cas.myorganization.com/serviceValidate"
# By default, devise_cas_authenticatable will create users. If you would
# rather require user records to already exist locally before they can
# authenticate via CAS, uncomment the following line.
# config.cas_create_user = false
# You can enable Single Sign Out, which by default is disabled.
config.cas_enable_single_sign_out = true
end
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/assets.rb | config/initializers/assets.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join('node_modules')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are
# already added.
Rails.application.config.assets.precompile += %w[print.css]
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/backtrace_silencers.rb | config/initializers/backtrace_silencers.rb | # frozen_string_literal: true
# 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 | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/mime_types.rb | config/initializers/mime_types.rb | # frozen_string_literal: true
# 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
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/secret_token.rb | config/initializers/secret_token.rb | # frozen_string_literal: true
# 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.
Reservations::Application.config.secret_key_base =
Rails.application.secrets.secret_key_base
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/deploy/staging.rb | config/deploy/staging.rb | # frozen_string_literal: true
# Simple Role Syntax
# ==================
# Supports bulk-adding hosts to roles, the primary server in each group
# is considered to be the first unless any hosts have the primary
# property set. Don't declare `role :all`, it's a meta role.
# role :app, %w{deploy@example.com}
# role :web, %w{deploy@example.com}
# role :db, %w{deploy@example.com}
# Extended Server Syntax
# ======================
# This can be used to drop a more detailed server definition into the
# server list. The second argument is a, or duck-types, Hash and is
# used to set extended properties on the server.
server 'localhost', user: 'hudson', roles: %w(web app db)
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult[net/ssh documentation](http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start).
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# And/or per server (overrides global)
# ------------------------------------
# server 'example.com',
# user: 'user_name',
# roles: %w{web app},
# ssh_options: {
# user: 'user_name', # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: 'please use keys'
# }
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/deploy/production.rb | config/deploy/production.rb | # frozen_string_literal: true
# Simple Role Syntax
# ==================
# Supports bulk-adding hosts to roles, the primary server in each group
# is considered to be the first unless any hosts have the primary
# property set. Don't declare `role :all`, it's a meta role.
# role :app, %w{deploy@example.com}
# role :web, %w{deploy@example.com}
# role :db, %w{deploy@example.com}
# Extended Server Syntax
# ======================
# This can be used to drop a more detailed server definition into the
# server list. The second argument is a, or duck-types, Hash and is
# used to set extended properties on the server.
server 'localhost', user: 'hudson', roles: %w(web app db)
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult[net/ssh documentation](http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start).
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# And/or per server (overrides global)
# ------------------------------------
# server 'example.com',
# user: 'user_name',
# roles: %w{web app},
# ssh_options: {
# user: 'user_name', # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: 'please use keys'
# }
# set crontab with whenever
namespace :deploy do
after :finishing, 'whenever:update_crontab'
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/environments/test.rb | config/environments/test.rb | # frozen_string_literal: true
# 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!
Rails.application.configure do
# Settings specified here will take precedence over those
# in config/application.rb.
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store
# 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
# Store uploaded files on the local file system in a temporary directory.
config.active_storage.service = :test
config.action_mailer.perform_caching = 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
# Set default host for mailer links
config.action_mailer.default_url_options = { host: '0.0.0.0:3000' }
# Randomize the order test cases are executed.
config.active_support.test_order = :random
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/environments/development.rb | config/environments/development.rb | # frozen_string_literal: true
Rails.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
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Use letter_opener for development mail testing
if ENV['USER'] == 'vagrant'
config.action_mailer.delivery_method = :letter_opener_web
else
config.action_mailer.delivery_method = :letter_opener
end
config.action_mailer.default_url_options = { host: '0.0.0.0:3000' }
# Store uploaded files on the local file system
# (see config/storage.yml for options).
config.active_storage.service = ENV.fetch('STORAGE_LOCATION', '')
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all
# assets, yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
config.after_initialize do
Bullet.enable = true
# Bullet.alert = true
Bullet.bullet_logger = true
Bullet.console = true
Bullet.rails_logger = true
# Bullet.bugsnag = true
# Bullet.add_footer = true
# Bullet.stacktrace_includes = [ 'your_gem', 'your_middleware' ]
# Disable Rack Mini Profiler in certain parts of the application
Rack::MiniProfiler.config.skip_paths ||= []
Rack::MiniProfiler.config.skip_paths << '/admin'
end
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
YaleSTC/reservations | https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/environments/production.rb | config/environments/production.rb | # frozen_string_literal: true
Rails.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
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either
# ENV["RAILS_MASTER_KEY"] or in config/master.key.
# This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Serve static assets
config.serve_static_assets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version`
# have moved to config/initializers/assets.rb
# Asset digests allow you to set far-future HTTP expiration dates on all
# assets, yet still be able to expire them through the digest params.
config.assets.digest = true
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# 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
# Store uploaded files on the local file system
# (see config/storage.yml for options).
config.active_storage.service = ENV.fetch('STORAGE_LOCATION', '')
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [
# 'http://example.com',
# /http:\/\/example.*/
# ]
# Force all access to the app over SSL, use Strict-Transport-Security,
# and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job
# (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "reservations_#{Rails.env}"
# Set domain
config.action_mailer.default_url_options = { host: "#{ENV['RAILS_HOST_NAME']}#{ENV['RAILS_RELATIVE_URL_ROOT']}" }
# Disable e-mails if environment variable is set
config.action_mailer.perform_deliveries = ENV['DISABLE_EMAILS'].nil?
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate
# delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(
# Syslog::Logger.new 'app-name'
# )
if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
else
# Rotate logs after 150 MB, keep 5 files
# See https://medium.com/@atinders/easy-log-rotation-with-rails-5-7b8d3c173461
config.logger = Logger.new(config.paths['log'].first, 5, 150.megabytes)
end
# set up PartyFoul
config.middleware.use('PartyFoul::Middleware') if ENV['PARTY_FOUL_TOKEN']
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# rubocop:disable Metrics/LineLength
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
# rubocop:enable Metrics/LineLength
end
| ruby | MIT | 2d5f0b2511a50787d79023bb3bbd148160dc3cc2 | 2026-01-04T17:43:15.442188Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/ci.rb | ci.rb | require 'rubygems'
require 'dash-ci'
CI.register('sinatras-hat') do
build :specs, 'spec spec/'
build :cucumber, 'cucumber -f progress features/'
end
CI.run('sinatras-hat', :token => ENV['DASH_TOKEN']) | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/support/env.rb | features/support/env.rb | require File.join(File.dirname(__FILE__), *%w[.. .. lib sinatras-hat])
require 'sinatra/test'
require 'acts_as_fu'
Sinatra::Test.module_eval do
def mock_app(base=Sinatra::Base, &block)
@app = Sinatra.new(base, &block)
end
end
World do
extend ActsAsFu
extend Sinatra::Test
end
require 'spec/expectations' | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/create_steps.rb | features/steps/create_steps.rb | When /^I make a POST request with valid form params$/ do
post "/people?person[name]=Pat"
end
When /^I make a POST request with invalid form params$/ do
post "/people?person[name]="
end
# When /^I make a POST request with valid serialized attributes for a valid format$/ do
# post "/people.xml", ({:person => { :name => "Pat" }}).to_xml
# end
Then /^a record is created$/ do
@record = Person.find_by_name("Pat")
@record.should_not be_nil
end
Then /^a record is not created$/ do
@record = Person.find_by_name("Pat")
@record.should be_nil
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/new_steps.rb | features/steps/new_steps.rb | When /^I get the new page for that record$/ do
get '/people/new'
end
When /^I get the new action with a valid format$/ do
get '/people/new.xml'
end
When /^I get the new action with an invalid format$/ do
get '/people/new.oops'
end
Then /^the body is a serialized new record$/ do
body.should == Person.new.to_xml
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/update_steps.rb | features/steps/update_steps.rb | When /^I make a put request with valid form params$/ do
put "/people/#{@record.to_param}?person[name]=UPDATED"
end
When /^I make a PUT request with invalid form params$/ do
put "/people/#{@record.to_param}?person[name]="
end
Then /^the record is updated$/ do
@record.reload
@record.name.should == "UPDATED"
end
Then /^the response redirects to the record show page$/ do
response.status.should == 302
response.location.should == "/people/#{@record.to_param}"
end
Then /^the record is not updated$/ do
@record.reload
@record.name.should == "Pat"
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/show_steps.rb | features/steps/show_steps.rb | # TODO Use acts_as_fu to build some actual models to test
When /^I get the show page for that record$/ do
get "/people/#{@record.to_param}"
end
When /^I get the show page for the non\-existent record$/ do
get "/people/87345873485763485"
end
When /^I make a request for that record with a format$/ do
get "/people/#{@record.to_param}.xml"
end
When /^I get the GET request for a non\-existent record with a format$/ do
get "/people/87345873485763485.xml"
end
Then /^the body is the serialized record$/ do
body.should == @record.to_xml
end
# Then /^the body is the custom serialized record$/ do
# end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/edit_steps.rb | features/steps/edit_steps.rb | When /^I get the edit page for that record$/ do
get "/people/#{@record.to_param}/edit"
end
When /^I get the edit page for a non\-existent record$/ do
get "/people/23472398732498734/edit"
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/only_steps.rb | features/steps/only_steps.rb | Given /^I mount the model for only the :index action$/ do
@app = mock_app do
set :views, File.join(File.dirname(__FILE__), '..', 'support', 'views')
# set :logging, true
mount Person do
only :index
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/format_steps.rb | features/steps/format_steps.rb | Given /^specify a custom 'ruby' formatter$/ do
# this is implemented in common_steps.rb
end
Then /^the body is the custom serialized record$/ do
@response.body.should == @record.inspect
end
Then /^the result should be custom serialized$/ do
@response.body.should == Person.all.inspect
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/common_steps.rb | features/steps/common_steps.rb | Before do
build_model(:people) do
string :name
timestamps
has_many :comments
validates_presence_of :name
end
build_model(:comments) do
integer :person_id
string :name
timestamps
belongs_to :person
end
Person.delete_all
Comment.delete_all
end
Given /^a model that has a record$/ do
@record = Person.create! :name => "Pat"
end
Given /^the record has children$/ do
@not_a_child = Comment.create! :name => "I should never show up!"
@child_record = @record.comments.create! :name => "Commented!"
end
Given /^a model that does not have a record$/ do
Person.all.should be_empty
@record = Person.new
class << @record
def to_param
"230934509834"
end
end
end
Given /^a mounted model$/ do
mock_app do
set :views, File.join(File.dirname(__FILE__), '..', 'support', 'views')
# set :logging, true
mount Person do
mount Comment
formats[:ruby] = proc { |data| data.inspect }
end
end
end
Given /^I mount the model$/ do
Given "a mounted model"
end
When /^I make a GET request for that record$/ do
get "/people/#{@record.to_param}"
end
When /^I make a GET request for that record using the '(\w+)' format$/ do |format|
get "/people/#{@record.to_param}.#{format}"
end
Then /^the body is empty$/ do
body.should be_empty
end
Then /^the status code is (\d+)$/ do |code|
response.status.should == code.to_i
end
Then /^I should see "(.*)"$/ do |text|
body.should =~ /#{text}/
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/destroy_steps.rb | features/steps/destroy_steps.rb | When /^I make a DELETE request to the path for that record$/ do
delete "/people/#{@record.to_param}"
end
When /^I make a DELETE request to a path for a non\-existent record$/ do
delete "/people/345345435"
end
Then /^the record gets destroyed$/ do
Person.find_by_id(@record.id).should be_nil
end
Then /^I am redirected to the index action$/ do
response.status.should == 302
response.location.should == '/people'
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/authenticated_steps.rb | features/steps/authenticated_steps.rb | Given /^I mount the model protecing the show action$/ do
@app = mock_app do
set :views, File.join(File.dirname(__FILE__), '..', 'support', 'views')
# set :logging, true
mount Person do
protect :show
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/index_steps.rb | features/steps/index_steps.rb | # TODO Use acts_as_fu to build some actual models to test
Given /^the model has some records$/ do
@record = Person.create :name => "Pat"
@frank = Person.create :name => "Frank"
end
When /^Make a GET request to the index without a format$/ do
get '/people'
end
When /^Make a GET request to the index with a known format$/ do
get '/people.xml'
end
When /^Make a GET request to the index using the '(\w+)' format$/ do |format|
get "/people.#{format}"
end
When /^I make a GET request to the index with an unknown format$/ do
get '/people.say_wha'
end
Then /^the result should be serialized$/ do
@response.body.should == Person.all.to_xml
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/header_steps.rb | features/steps/header_steps.rb | Then /^"(.*)" should be the record "(.*)" time$/ do |header, key|
DateTime.parse(response.headers[header].to_s).should == @record.send(key)
end
Then /^"(.*)" should be set$/ do |header|
response.headers[header].should_not be_blank
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/features/steps/nested_steps.rb | features/steps/nested_steps.rb | When /^Make a GET request to the nested index without a format$/ do
get "/people/#{@record.id}/comments"
end
When /^Make a GET request to the nested index with a valid format$/ do
get "/people/#{@record.id}/comments.xml"
end
Then /^the body is the serialized list of children$/ do
@response.body.should == @record.comments.to_xml
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/response_spec.rb | spec/response_spec.rb | require 'spec/spec_helper'
class Article; end
describe Sinatra::Hat::Response do
attr_reader :maker, :response, :request
def new_response(maker=@maker)
Sinatra::Hat::Response.new(maker, request)
end
before(:each) do
@maker = new_maker
@request = fake_request
stub(request.options).views { fixture('views') }
end
describe "render()" do
describe "rendering templates" do
it "renders the index template" do
mock.proxy(request).erb :"articles/index"
new_response.render(:index)
end
it "renders the show template" do
mock.proxy(request).erb :"articles/show"
new_response.render(:show)
end
end
context "when there are options passed" do
it "sends the options to the request" do
t = Time.now
mock(request).last_modified t
new_response.render(:show, :last_modified => t)
end
end
context "when there is no views dir" do
before(:each) do
stub(request.options).views { nil }
end
it "raises Sinatra::NoTemplateError" do
proc {
new_response.render(:show)
}.should raise_error(Sinatra::NoTemplateError)
end
end
context "when the view does not exist" do
it "raises Sinatra::NoTemplateError" do
proc {
new_response.render(:nonsense)
}.should raise_error(Sinatra::NoTemplateError)
end
end
end
describe "redirect()" do
context "when passed a path" do
it "redirects to the given path" do
mock(request).redirect("/articles")
new_response.redirect("/articles")
end
end
context "when passed a record" do
before(:each) do
stub(@article = Article.new).id { 2 }
end
context "when passed a record for the current maker" do
it "redirects to the resource path for that data" do
mock(request).redirect("/articles/2")
new_response.redirect(@article)
end
end
context "when passed a record for the current maker" do
before(:each) do
@article.save!
@comment = @article.comments.create!
@child_maker = new_maker(Comment, :parent => @maker)
end
it "redirects to the resource path for that data" do
mock(request).redirect("/articles/#{@article.to_param}")
new_response(@child_maker).redirect(@article)
end
end
end
context "when passed a symbol" do
before(:each) do
stub(@article = Article.new).id { 2 }
end
it "can redirect to the :index path" do
mock(request).redirect("/articles")
new_response.redirect(:index)
end
it "can redirect to the :show path" do
mock(request).redirect("/articles/2")
new_response.redirect(:show, @article)
end
it "can redirect to the :new path" do
mock(request).redirect("/articles/new")
new_response.redirect(:new)
end
it "can redirect to the :edit path" do
mock(request).redirect("/articles/2/edit")
new_response.redirect(:edit, @article)
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/extendor_spec.rb | spec/extendor_spec.rb | require 'spec/spec_helper'
describe Sinatra::Hat::Extendor do
describe "mount" do
context "when used at top level" do
it "takes a klass" do
proc {
mock_app { mount(Article) }
}.should_not raise_error
end
it "uses Rack::MethodOverride" do
app = mock_app
mock.proxy(app).use(Rack::MethodOverride)
app.class_eval { mount(Article) }
end
it "takes an options hash" do
proc {
mock_app { mount(Article, :only => [:index]) }
}.should_not raise_error
end
it "instantiates a new Sinatra::Hat::Maker" do
mock.proxy(Sinatra::Hat::Maker).new(Article, { })
mock_app { mount(Article) }
end
it "instance_eval's the block in the new maker" do
mock.proxy(maker = new_maker).instance_eval
mock.proxy(Sinatra::Hat::Maker).new(Article, { }) { maker }
mock_app { mount(Article, &proc { }) }
end
it "generates routes" do
mock.proxy.instance_of(Sinatra::Hat::Maker).setup(anything)
mock_app { mount(Article) }
end
end
context "when used in nested #mount calls" do
attr_reader :app, :maker
before(:each) do
@app = mock_app
@maker = new_maker(Article)
maker.setup(app)
end
it "takes a klass" do
proc {
maker.mount(Comment)
}.should_not raise_error
end
it "takes an options hash" do
proc {
maker.mount(Comment, :only => :index)
}.should_not raise_error
end
it "instantiates a new Sinatra::Hat::Maker" do
mock.proxy(Sinatra::Hat::Maker).new(Comment, { })
maker.mount(Comment)
end
it "sets the :parent option" do
mock.proxy(Sinatra::Hat::Maker).new(Comment, { })
maker.mount(Comment).parent.should == maker
end
it "generates routes" do
mock.proxy.instance_of(Sinatra::Hat::Maker).setup(app)
maker.mount(Comment)
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/router_spec.rb | spec/router_spec.rb | require 'spec/spec_helper'
describe Sinatra::Hat::Router do
before(:each) do
build_models!
end
describe "initialization" do
it "takes an instance of Maker" do
proc {
maker = new_maker
Sinatra::Hat::Router.new(maker)
}.should_not raise_error
end
end
describe "#generate" do
attr_reader :app, :maker, :router
before(:each) do
@app = mock_app { set :views, fixture('views') }
@maker = new_maker
@router = Sinatra::Hat::Router.new(maker)
stub.proxy(app).get(anything)
end
it "takes a Sinatra app" do
router.generate(app)
end
describe "abiding by the maker's :only option" do
before(:each) do
maker.only :index, :show
router.generate(app)
end
it "should only have the limited options" do
mock(app).put(anything).never
mock(app).delete(anything).never
post '/articles'
response.status.should == 404
put "/articles/#{@article.to_param}"
response.status.should == 404
delete "/articles/#{@article.to_param}"
response.status.should == 404
end
end
describe "generating index route" do
it "calls the block, passing the request" do
router.generate(app)
mock.proxy(maker).handle(:index, anything) { "" }
get '/articles.yaml'
end
end
describe "generating show route" do
it "calls the block, passing the request" do
router.generate(app)
mock.proxy(maker).handle(:show, anything) { "" }
get '/articles/1.yaml'
end
end
describe "generating create route" do
it "calls the block, passing the request" do
router.generate(app)
mock(maker).handle(:create, anything)
post '/articles', "maker[name]" => "Pat"
end
end
describe "generating new route" do
it "calls the block, passing the request" do
router.generate(app)
mock.proxy(maker).handle(:new, anything) { "" }
get '/articles/new'
end
end
describe "generating destroy route" do
it "calls the block, passing the request" do
router.generate(app)
mock.proxy(maker).handle(:destroy, anything) { "" }
delete "/articles/#{@article.to_param}"
end
end
describe "generating edit route" do
it "calls the block, passing the request" do
router.generate(app)
mock.proxy(maker).handle(:edit, anything) { "" }
get "/articles/#{@article.to_param}/edit"
end
end
describe "generating update route" do
it "calls the block, passing the request" do
router.generate(app)
mock.proxy(maker).handle(:update, anything) { "" }
put "/articles/#{@article.to_param}"
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/model_spec.rb | spec/model_spec.rb | require 'spec/spec_helper'
describe Sinatra::Hat::Model do
attr_reader :model, :maker, :fake_request
before(:each) do
build_models!
end
def new_model(maker=new_maker)
Sinatra::Hat::Model.new(maker)
end
describe "initialization" do
it "takes an instance of Maker" do
proc {
maker = new_maker
new_model(maker)
}.should_not raise_error
end
end
describe "find_last_modified" do
before(:each) do
@last_modified_article = Article.create!
end
it "returns the last modified record" do
new_model.find_last_modified([@article, @last_modified_article]).should == @last_modified_article
end
end
describe "all()" do
before(:each) do
@maker = new_maker
@model = new_model(maker)
end
it "takes the params" do
proc {
model.all({ })
}.should_not raise_error
end
it "calls the finder" do
mock.proxy(maker.options[:finder]).call(Article, { })
model.all({ }).should == Article.all
end
end
describe "foreign_key" do
before(:each) do
@maker = new_maker
@model = new_model(maker)
end
it "returns the singular name with _id" do
model.foreign_key.should == "#{model.singular}_id".to_sym
end
end
describe "find_owner" do
before(:each) do
@maker = new_maker
@model = new_model(maker)
end
it "uses the foreign key to search the params" do
model.find_owner(model.foreign_key => @article.to_param).should == @article
end
end
describe "find()" do
attr_reader :article
before(:each) do
@maker = new_maker
@model = new_model(maker)
end
it "takes the params" do
proc {
model.find(:id => @article.to_param)
}.should_not raise_error
end
it "calls for the :record" do
mock.proxy(maker.options[:record]).call(Article, { :id => @article.to_param })
model.find(:id => @article.to_param).should == @article
end
end
describe "plural" do
it "returns snakecased, pluralized form of model name" do
new_model(new_maker(Article)).plural.should == "articles"
end
end
describe "singular" do
it "returns snakecased, singular form of model name" do
new_model(new_maker(Article)).singular.should == "article"
end
end
describe "update" do
it "finds the record" do
model = new_model
mock.proxy(model).find(anything) { @article }
mock.proxy(@article).attributes = { "name" => "Hooray!" }
model.update("id" => @article.to_param, "article[name]" => "Hooray!")
end
end
describe "new" do
context "when there is no parent" do
it "instantiates a new model object" do
mock.proxy(Article).new(anything)
new_model.new
end
it "railsifies params passed through" do
mock.proxy(Article).new("name" => "The article")
new_model.new("article[name]" => "The article")
end
end
context "when there is a parent" do
attr_reader :article
before(:each) do
@maker = new_maker(Article)
@maker.setup(mock_app)
child_maker = maker.mount(Comment)
child_maker.parent = maker
@child_model = new_model(child_maker)
end
context "when there is an association proxy" do
it "uses the association proxy" do
@child_model.new(:article_id => @article.to_param)
end
end
context "when there isn't an association proxy" do
it "just returns the klass" do
mock.proxy(Comment).new(anything)
new_model(maker.mount(Comment)).new
end
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/maker_spec.rb | spec/maker_spec.rb | require 'spec/spec_helper'
class Article; end
class Comment; end
describe Sinatra::Hat::Maker do
attr_reader :model, :maker, :request
describe "initializing" do
it "takes a klass" do
proc {
new_maker(Article)
}.should_not raise_error
end
it "takes options" do
proc {
new_maker(Article, :only => :index)
}.should_not raise_error
end
it "merges options hash with defaults" do
maker = new_maker(Article, :only => :index)
maker.options[:only].should == :index
end
end
describe "setup" do
before(:each) do
stub.instance_of(Sinatra::Hat::Router).generate(:app)
end
it "stores reference to app" do
maker = new_maker
maker.setup(:app)
maker.app.should == :app
end
end
it "has a klass" do
new_maker(Article).klass.should == Article
end
describe "protect" do
before(:each) do
@maker = new_maker
end
it "sets the protected actions" do
maker.protect :index, :show
maker.protect.should == [:index, :show]
end
it "can set the protected actions to :all" do
maker.protect :all
maker.protect.should == maker.only
end
it "can set the credentials" do
maker.protect :username => "admin", :password => "awesome", :realm => "awesome app"
maker.credentials.should == { :username => "admin", :password => "awesome", :realm => "awesome app" }
end
end
describe "handling actions" do
before(:each) do
@request = fake_request
@maker = new_maker
stub(Sinatra::Hat::Maker.actions[:index])[:fn].returns proc { |passed_request| [self, passed_request] }
end
it "takes an action and instance_exec's its event handler" do
mock(Sinatra::Hat::Maker.actions[:index])[:fn].returns proc { |passed_request| [self, passed_request] }
maker.handle(:index, request).should == [maker, request]
end
context "when the action is protected" do
before(:each) do
maker.protect :index
end
context "when the user is not authenticated" do
it "protects the action" do
proc {
maker.handle(:index, request)
}.should throw_symbol(:halt)
end
end
context "when the user is authenticated" do
before(:each) do
request.env['REMOTE_USER'] = 'hello'
end
it "allows the request" do
proc {
maker.handle(:index, request)
}.should_not throw_symbol(:halt)
end
end
end
context "when the action is not part of the :only list" do
before(:each) do
maker.only :show
end
it "returns 404" do
mock.proxy(request).error(404)
catch(:halt) { maker.handle(:index, request) }
end
end
end
describe "default options" do
before(:each) do
@maker = new_maker(Article)
end
it "has a default options hash" do
maker.options.should_not be_nil
end
describe ":only" do
it "returns all actions" do
maker.options[:only].should include(:index, :show, :new, :create, :edit, :update, :destroy)
end
it "is methodized" do
maker.only.should == maker.options[:only]
end
it "has methodized setter" do
maker.only :index, :show
maker.only.should have(2).entries
maker.only.should include(:index)
maker.only.should include(:show)
end
end
describe ":formats" do
it "is an empty hash" do
maker.options[:formats].should == { }
end
it "is methodized" do
maker.formats.should === maker.options[:formats]
end
end
describe ":to_param" do
it "is :id by default" do
maker.options[:to_param].should == :id
end
it "is methodized" do
maker.to_param.should == :id
end
it "has methodized setter" do
maker.to_param :permalink
maker.to_param.should == :permalink
end
end
describe ":parent" do
it "is nil" do
maker.options[:parent].should be_nil
end
it "is methodized" do
maker.parent.should === maker.options[:parent]
end
end
describe ':format' do
it 'is nil by default' do
maker.options[:format].should be_nil
maker.options.should have_key(:format)
end
it 'is methodized' do
maker.options[:format] = :json
maker.format.should == :json
end
it 'has methodized setter' do
maker.format :json
maker.format.should == :json
end
end
describe ":protect" do
it "is empty by default" do
maker.options[:protect].should be_empty
end
it "is methodized" do
maker.protect.should === maker.options[:protect]
end
it "has methodized setter" do
maker.protect :index, :show
maker.protect.should == [:index, :show]
end
end
describe ":finder" do
it "finds all for the model" do
mock(Article).all
maker.options[:finder][Article, { }]
end
end
describe ":authenticator" do
it "finds all for the model" do
mock(Article).all
maker.options[:finder][Article, { }]
end
it "has a block setter" do
fn = proc { |u, p| [u, p] }
maker.authenticator(&fn)
maker.authenticator[:user, :pass].should == [:user, :pass]
end
end
describe ":credentials" do
it "has username" do
maker.options[:credentials][:username].should_not be_nil
end
it "has password" do
maker.options[:credentials][:password].should_not be_nil
end
it "has realm" do
maker.options[:credentials][:realm].should_not be_nil
end
end
describe ":record" do
it "loads a single record" do
mock(Article).find_by_id(2)
maker.options[:record][Article, { :id => 2 }]
end
end
end
describe "finder" do
context "when no block is provided" do
it "returns the finder option" do
maker = new_maker
maker.finder.should == maker.options[:finder]
end
end
context "when a block is provided" do
it "sets the finder option" do
maker = new_maker
block = proc { |model, params| model.find_by_id(params[:id]) }
maker.finder(&block)
maker.options[:finder].should == block
end
end
end
describe "record" do
context "when no block is provided" do
it "returns the record option" do
maker = new_maker
maker.record.should == maker.options[:record]
end
end
context "when a block is provided" do
it "sets the record option" do
maker = new_maker
block = proc { |model, params| model.find_by_id(params[:id]) }
maker.record(&block)
maker.options[:record].should == block
end
end
end
describe "prefix" do
context "when used as a method" do
before(:each) do
@maker = new_maker(Article)
end
it "is a getter if called without argument" do
maker.prefix.should == maker.options[:prefix]
end
it "is a setter if called with an argument" do
maker.prefix 'super/heroes'
maker.prefix.should == 'super/heroes'
maker.prefix.should == maker.options[:prefix]
end
end
context "when specified as an option" do
it "returns the option value" do
new_maker(Article, :prefix => "posts").prefix.should == "posts"
end
end
context "when it's not specified as an option" do
it "returns the pluralized, downcased klass name" do
new_maker(Article).prefix.should == "articles"
end
it "snakecases" do
stub(klass = Class.new).name { "AwesomePerson" }
new_maker(klass).prefix.should == 'awesome_people'
end
end
end
describe "parents" do
context "when there are none" do
it "is empty" do
new_maker.parents.should be_empty
end
end
context "when there is one" do
it "includes the parent" do
parent = new_maker(Article)
child = new_maker(Comment, :parent => parent)
child.parents.should == [parent]
end
end
context "when there are many" do
it "includes all ancestors" do
grand_parent = new_maker(Article)
parent = new_maker(Article, :parent => grand_parent)
child = new_maker(Comment, :parent => parent)
child.parents.should == [grand_parent, parent]
end
end
end
describe "#model" do
it "returns an instance of Sinatra::Hat::Model" do
maker = new_maker
mock.proxy(Sinatra::Hat::Model.new(maker))
maker.model
end
end
describe "#responder" do
it "returns an instance of Sinatra::Hat::Responder" do
maker = new_maker
mock.proxy(Sinatra::Hat::Responder.new(maker))
maker.responder
end
end
describe "generating routes" do
it "generates routes for maker instance" do
maker = new_maker
router = Sinatra::Hat::Router.new(maker)
mock.proxy(Sinatra::Hat::Router).new(maker) { router }
mock(router).generate(maker.app)
maker.generate_routes!
end
end
describe "#after" do
before(:each) do
@maker = new_maker
end
it "takes the name of an action" do
proc {
maker.after(:create) { }
}.should_not raise_error
end
it "passes a new hash mutator to the block" do
maker.after(:create) { |arg| arg }.should be_kind_of(Sinatra::Hat::HashMutator)
end
it "lets you alter the default options" do
maker.after(:create) do |on|
on.success { :new_default! }
end
maker.responder.defaults[:create][:success][].should == :new_default!
end
describe "when there are nested resources" do
before(:each) do
@child_maker = new_maker(Comment)
@child_maker.parent = @maker
end
it "mutates the child's response" do
@child_maker.after(:create) do |on|
on.success { :child_response }
end
@child_maker.responder.defaults[:create][:success][].should == :child_response
@maker.responder.defaults[:create][:success].should_not === @child_maker.responder.defaults[:create][:success]
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/responder_spec.rb | spec/responder_spec.rb | require 'spec/spec_helper'
describe Sinatra::Hat::Responder do
attr_reader :maker, :responder
def new_responder(maker=@maker)
Sinatra::Hat::Responder.new(maker)
end
before(:each) do
build_models!
@maker = new_maker
end
describe "initialization" do
it "takes an instance of Maker" do
proc {
Sinatra::Hat::Responder.new(@maker)
}.should_not raise_error
end
end
describe "success" do
context "when there's a default format" do
before(:each) do
@maker.format :json
end
it 'serializes the response with the default format' do
request = fake_request
responder = new_responder
responder.success(:show, request, :article).should == :article.to_json
end
end
context "when there's a format" do
it "serializes the response" do
request = fake_request(:format => "yaml")
mock.proxy(responder = new_responder).serialize(:article, "yaml")
responder.success(:show, request, :article)
end
end
context "when there's no format" do
it "calls that action's :success proc" do
request = fake_request
mock.proxy(Sinatra::Hat::Response).new(maker, request) do |response|
mock.proxy(response).render(anything)
end
new_responder.success(:show, request, :article)
end
end
describe "assigning instance variables" do
context "when the result is a collection" do
it "assigns the plural instance variable in the request" do
request = fake_request
new_responder.success(:index, request, [:articles])
request.instance_eval { @articles }.should == [:articles]
end
end
context "when the result is not a collection" do
it "assigns the singular instance variable in the request" do
request = fake_request
new_responder.success(:show, request, :article)
request.instance_eval { @article }.should == :article
end
end
describe "assigning parent instance variables" do
before(:each) do
@parent_maker = new_maker(Article)
@child_maker = new_maker(Comment)
@responder = @child_maker.responder
end
end
end
end
describe "failure" do
# context "when there's a format" do
# it "serializes the response" do
# request = fake_request(:format => "yaml")
# mock.proxy(responder = new_responder).serialize("yaml", :article)
# responder.success(:show, request, :article)
# end
# end
context "when there's no format" do
it "calls that action's :failure proc" do
request = fake_request
mock.proxy(Sinatra::Hat::Response).new(maker, request) do |response|
mock(response).redirect(anything)
end
new_responder.failure(:show, request, :article)
end
end
end
describe "serialize()" do
before(:each) do
@responder = new_responder
end
context "when there is no formatter" do
context "when the data responds to to_*" do
it "serializes data and gets mime type" do
response, mime = responder.serialize([:article], "yaml")
response.should == [:article].to_yaml
mime.should == 'text/yaml'
end
end
context "when the data doesn't respond to to_*" do
it "returns nil" do
responder.serialize([:article], "say_what").should be_nil
end
end
end
context "when there is a formatter" do
before(:each) do
maker.formats[:yaml] = proc { |data| [data, :formatted].inspect }
end
it "returns serialized data and the mime type" do
response = responder.serialize(:article, "yaml")
response.should == [[:article, :formatted].inspect, 'text/yaml']
end
end
end
describe "custom responses using #on" do
before(:each) do
@responder = new_responder
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/hash_mutator_spec.rb | spec/hash_mutator_spec.rb | require 'spec/spec_helper'
describe Sinatra::Hat::HashMutator do
attr_reader :mutator, :hash
before(:each) do
@hash = {
:success => proc { :ftw! },
:failure => proc { :fail }
}
@mutator = Sinatra::Hat::HashMutator.new(hash)
end
it "lets you alter the success key of the passed in hash" do
mutator.success { :pwnd! }
hash[:success][].should == :pwnd!
end
it "lets you alter the failure key of the passed in hash" do
mutator.failure { :pwnd! }
hash[:failure][].should == :pwnd!
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/resource_spec.rb | spec/resource_spec.rb | require 'spec/spec_helper'
describe Sinatra::Hat::Resource do
before(:each) do
build_models!
end
describe "initialization" do
it "takes an instance of Maker" do
proc {
Sinatra::Hat::Resource.new(new_maker)
}.should_not raise_error
end
end
describe "paths" do
context "when maker has no parent" do
before(:each) do
maker = new_maker(Article)
@resource = Sinatra::Hat::Resource.new(maker)
end
it "returns normal resource path" do
@resource.path('/:id').should == "/articles/:id"
end
it "can return :root path" do
@resource.path('/:id').should == "/articles/:id"
end
it "can return path for model object" do
@resource.path('/:id', @article).should == "/articles/#{@article.to_param}"
end
end
context "when maker has a parent" do
before(:each) do
@child = new_maker(Comment, :parent => new_maker(Article))
@resource = Sinatra::Hat::Resource.new(@child)
end
it "returns nested resource path" do
@resource.path('/:id').should == "/articles/:article_id/comments/:id"
end
it "doesn't mutate parents" do # regression test
@resource.path('/:id').should == "/articles/:article_id/comments/:id"
@resource.path('/:id').should == "/articles/:article_id/comments/:id"
end
it "can return path for model object" do
@resource.path('/:id', @comment).should == "/articles/#{@article.to_param}/comments/#{@comment.to_param}"
end
end
context "when maker has multiple parents" do
before(:each) do
build_model(:replies) { integer :comment_id; belongs_to :comment }
@reply = Reply.create! :comment => @comment
@child = new_maker(Comment, :parent => new_maker(Article))
@grand_child = new_maker(Reply, :parent => @child)
@resource = Sinatra::Hat::Resource.new(@grand_child)
end
it "returns nested resource path" do
@resource.path('/:id').should == "/articles/:article_id/comments/:comment_id/replies/:id"
end
it "can return path for model object" do
@resource.path('/:id', @reply).should == "/articles/#{@article.to_param}/comments/#{@comment.to_param}/replies/#{@reply.to_param}"
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/spec_helper.rb | spec/spec_helper.rb | ARGV.clear
$LOAD_PATH << File.join(File.dirname(__FILE__), '..')
require 'rubygems'
require 'spec'
require 'rr'
require 'sinatra/base'
require 'sinatra/test'
require 'sinatra/test/rspec'
# What we're testing:
require 'lib/sinatras-hat'
# Tired of stupid mocks
require 'acts_as_fu/base'
def fixture(path)
File.join(File.dirname(__FILE__), 'fixtures', path)
end
Spec::Runner.configure do |config|
config.mock_with :rr
config.include Sinatra::Test
end
include ActsAsFu
build_model(:articles) do
string :name
string :description
timestamps
has_many :comments
def self.all
super(:order => 'created_at DESC')
end
end
build_model(:comments) do
string :name
integer :article_id
belongs_to :article
end
module Sinatra::Test
# Sets up a Sinatra::Base subclass defined with the block
# given. Used in setup or individual spec methods to establish
# the application.
def mock_app(base=Sinatra::Base, &block)
@app = Sinatra.new(base, &block)
end
end
def build_models!
Article.delete_all
Comment.delete_all
@article = Article.create! :name => "An article"
@non_child = @article.comments.create! :name => "Non child!"
@comment = @article.comments.create! :name => "The child comment"
end
def new_maker(klass=Article, *args, &block)
Sinatra::Hat::Maker.new(klass, *args, &block)
end
def fake_request(options={})
app = Sinatra.new
app.set :views, fixture("views")
request = app.new
stub(request).env.returns({ })
stub(request).params.returns(options)
stub(request).response.returns(Sinatra::Response.new)
stub(request).last_modified(anything)
stub(request).etag(anything)
request
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/actions/show_spec.rb | spec/actions/show_spec.rb | require 'spec/spec_helper'
describe "handle show" do
attr_reader :maker, :app, :request
before(:each) do
build_models!
mock_app { }
@maker = new_maker(Article)
@request = fake_request(:id => @article.to_param)
end
def handle(*args)
maker.handle(:show, *args)
end
it "takes a request" do
handle(request)
end
it "loads correct record" do
mock.proxy(maker.model).find(:id => @article.to_param) { :article }
handle(request)
end
describe "rendering a successful response" do
context "when there's a :format param" do
before(:each) do
params = { :format => "yaml", :id => @article.to_param }
@request = fake_request(params)
stub(maker.model).find(params).returns(@article)
end
it "sets last_modified header" do
mock(request).last_modified(@article.updated_at)
handle(request)
end
it "sets ETag header" do
mock(request).etag(anything)
handle(request)
end
end
context "when there's no :format param" do
before(:each) do
params = { :id => @article.to_param }
@request = fake_request(params)
stub(maker.model).find(anything).returns(@article)
end
it "uses the success response" do
mock.proxy(maker.responder).success(:show, request, @article)
handle(request)
end
it "sets last_modified param" do
mock(request).last_modified(@article.updated_at)
handle(request)
end
it "sets ETag header" do
mock(request).etag(anything)
handle(request)
end
end
end
describe "rendering not_found" do
before(:each) do
stub(maker.model).find(request.params).returns(nil)
stub(request).not_found # because it throws :halt otherwise
end
it "returns not_found" do
mock(request).not_found
handle(request)
end
it "does not set last_modified param" do
mock(request).last_modified(@article.updated_at).never
handle(request)
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/actions/update_spec.rb | spec/actions/update_spec.rb | require 'spec/spec_helper'
describe "handle create" do
attr_reader :maker, :app, :request, :article
before(:each) do
build_models!
mock_app { }
@maker = new_maker(Article)
@request = fake_request("article[name]" => "Hooray!")
stub(request).redirect(anything)
end
def handle(*args)
maker.handle(:update, *args)
end
describe "when the record doesn't exist" do
before(:each) do
stub(maker.model).find(anything) { nil }
end
it "returns not_found" do
mock.proxy(request).not_found
catch(:halt) { handle(request) }
end
end
describe "attempting to update a record" do
it "finds a record and updates its attributes" do
mock.proxy(article).attributes = { "name" => "Hooray!" }
mock.proxy(article).save
mock.proxy(maker.model).find(anything) { article }
handle(request)
end
context "when the save is successful" do
before(:each) do
stub(maker.model).find(anything).returns(article)
stub(article).save { true }
end
context "when there's no format" do
it "redirects to that record's path" do
mock(request).redirect("/articles/#{article.id}")
mock.proxy(maker.responder).success(:update, request, article)
handle(request)
end
end
# context "when there is a format" do
# it "serializes the record" do
# request_with_format = fake_request(:format => "yaml")
# mock.proxy(maker.responder).serialize("yaml", article)
# handle(request_with_format)
# end
# end
end
context "when the save is not successful" do
before(:each) do
stub(maker.model).find(anything).returns(article)
stub(article).save { false }
end
context "when there's no format" do
it "renders edit template" do
mock(request).erb :"articles/edit"
mock.proxy(maker.responder).failure(:update, request, article)
handle(request)
end
end
# context "when there is a format" do
# it "serializes the record" do
# request_with_format = fake_request(:format => "yaml")
# mock.proxy(maker.responder).serialize("yaml", article)
# handle(request_with_format)
# end
# end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/actions/new_spec.rb | spec/actions/new_spec.rb | require 'spec/spec_helper'
describe "handle index" do
attr_reader :maker, :app, :request
before(:each) do
build_models!
mock_app { }
@maker = new_maker(Article)
@request = fake_request
end
def handle(*args)
maker.handle(:new, *args)
end
it "takes a request" do
maker.handle(:new, request)
end
it "loads a new record" do
mock.proxy(maker.model).new(anything) { :article }
handle(request)
end
describe "rendering a response" do
context "when there's no :format param" do
before(:each) do
@request = fake_request
stub(maker.model).new(anything).returns(:article)
end
it "renders the index template" do
mock.proxy(maker.responder).success(:new, request, :article)
handle(request)
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/actions/create_spec.rb | spec/actions/create_spec.rb | require 'spec/spec_helper'
describe "handle create" do
attr_reader :maker, :app, :request, :article
before(:each) do
build_models!
mock_app { }
@maker = new_maker(Article)
@request = fake_request("article[name]" => "The article")
stub(request).redirect(anything)
end
def handle(*args)
maker.handle(:create, *args)
end
it "instantiates a new record and saves it" do
mock.proxy(article = Article.new).save
mock.proxy(maker.model).new("article[name]" => "The article") { article }
handle(request)
end
describe "responding" do
attr_reader :new_article
before(:each) do
@new_article = Article.new
end
context "when the save is successful" do
before(:each) do
stub(Article).new(anything).returns(new_article)
end
context "when there's no format" do
it "redirects" do
mock(request).redirect(anything)
mock.proxy(maker.responder).success(:create, request, new_article)
handle(request)
end
end
end
context "when the save is not successful" do
before(:each) do
stub(Article).new(anything).returns(new_article)
stub(new_article).save { false }
end
context "when there's no format" do
it "renders edit template" do
mock(request).erb :"articles/new"
mock.proxy(maker.responder).failure(:create, request, new_article)
handle(request)
end
end
# context "when there is a format" do
# it "serializes the record" do
# request_with_format = fake_request(:format => "yaml")
# mock.proxy(maker.responder).serialize("yaml", article)
# handle(request_with_format)
# end
# end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/actions/destroy_spec.rb | spec/actions/destroy_spec.rb | require 'spec/spec_helper'
describe "handle destroy" do
attr_reader :maker, :app, :request, :article
before(:each) do
build_models!
mock_app { }
@maker = new_maker(Article)
@request = fake_request(:id => @article.to_param)
stub(maker.model).find(:id => @article.to_param) { @article }
stub(request).redirect(anything)
end
def handle(*args)
maker.handle(:destroy, *args)
end
it "takes a request" do
handle(request)
end
context "when the record exists" do
it "loads correct record" do
mock.proxy(maker.model).find(:id => @article.to_param) { article }
handle(request)
end
it "destroys the record" do
mock.proxy(article).destroy
handle(request)
end
describe "rendering a response" do
before(:each) do
params = { :id => @article.to_param }
@request = fake_request(params)
stub(maker.model).find(params).returns(article)
end
it "redirects to the index" do
mock(request).redirect('/articles')
handle(request)
end
end
end
context "when the record does not exist" do
before(:each) do
stub(maker.model).find(:id => @article.to_param) { nil }
end
it "returns not_found" do
mock.proxy(request).not_found
catch(:halt) { handle(request) }
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/actions/edit_spec.rb | spec/actions/edit_spec.rb | require 'spec/spec_helper'
describe "handle show" do
attr_reader :maker, :app, :request
before(:each) do
build_models!
mock_app { }
@maker = new_maker(Article)
@request = fake_request(:id => @article.to_param)
end
def handle(*args)
maker.handle(:edit, *args)
end
it "takes a request" do
handle(request)
end
describe "rendering not_found" do
before(:each) do
stub(maker.model).find(request.params).returns(nil)
stub(request).not_found # because it throws :halt otherwise
end
it "returns not_found" do
mock(request).not_found
handle(request)
end
end
describe "rendering a successful response" do
it "loads correct record" do
mock.proxy(maker.model).find(:id => @article.to_param) { :article }
handle(request)
end
context "when there's no :format param" do
before(:each) do
params = { :id => @article.to_param }
@request = fake_request(params)
stub(maker.model).find(params).returns(:article)
end
it "renders the show template" do
mock.proxy(maker.responder).success(:edit, request, :article)
handle(request)
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/spec/actions/index_spec.rb | spec/actions/index_spec.rb | require 'spec/spec_helper'
describe "handle index" do
attr_reader :maker, :app, :request
before(:each) do
build_models!
mock_app { }
@maker = new_maker(Article)
@request = fake_request
end
def handle(*args)
maker.handle(:index, *args)
end
it "takes a request" do
maker.handle(:index, request)
end
it "loads all records" do
mock.proxy(maker.model).all(anything) { [] }
handle(request)
end
describe "rendering a response" do
context "when there's a :format param" do
before(:each) do
@newest_article = Article.create!
@request = fake_request(:format => "yaml")
stub(maker.model).all(anything).returns([@newest_article, @article])
end
it "sets ETag header" do
mock(request).etag(anything)
handle(request)
end
describe "setting the last_modified params" do
context "when the last record was the most recently updated" do
it "sets last_modified param to the last updated record's updated_at" do
mock(request).last_modified(anything)
handle(request)
end
end
context "when the last record was not the most recently updated" do
before(:each) do
@article.update_attribute :name, "Updated recently"
end
it "sets last_modified param to the last updated record's updated_at" do
mock(request).last_modified(anything)
handle(request)
end
end
end
end
context "when there's no :format param" do
before(:each) do
@request = fake_request
stub(maker.model).all(anything).returns([:article])
end
it "renders the index template" do
mock.proxy(maker.responder).success(:index, request, [:article])
handle(request)
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/example/app-with-cache.rb | example/app-with-cache.rb | require File.dirname(__FILE__) + '/lib/common.rb'
require 'rack/cache'
class MountedApp < Sinatra::Base
set :app_file, __FILE__
set :logging, true
use Rack::Cache do
set :verbose, true
set :metastore, 'heap:/'
set :entitystore, 'heap:/'
end
get '/' do
redirect '/posts'
end
mount(Post) do
finder { |model, params| model.all }
record { |model, params| model.first(:id => params[:id]) }
# Mount children as a nested resource
mount(Comment) do
finder { |model, params| model.all }
record { |model, params| model.first(:id => params[:id]) }
end
end
end
MountedApp.run! | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/example/app-with-auth.rb | example/app-with-auth.rb | require File.dirname(__FILE__) + '/lib/common.rb'
class MountedApp < Sinatra::Base
set :app_file, __FILE__
set :logging, true
mount(Post) do
protect :index,
:username => 'bliggety',
:password => 'blam',
:realm => "Use Protection"
end
run!
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/example/app.rb | example/app.rb | require File.dirname(__FILE__) + '/lib/common.rb'
class MountedApp < Sinatra::Base
set :app_file, __FILE__
set :logging, true
get '/' do
"You created a post, and this is a custom response."
end
mount(Post) do
finder { |model, params| model.all }
record { |model, params| model.first(:id => params[:id]) }
# Mount children as a nested resource
mount(Comment) do
finder { |model, params| model.all }
record { |model, params| model.first(:id => params[:id]) }
end
end
end
MountedApp.run! if __FILE__ == $0 | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/example/simple-app.rb | example/simple-app.rb | require File.dirname(__FILE__) + '/lib/common.rb'
# This is the simplest possible app
mount(Post) | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/example/lib/common.rb | example/lib/common.rb | $LOAD_PATH << File.join(File.dirname(__FILE__), '..', '..')
$LOAD_PATH << File.join(File.dirname(__FILE__))
require 'rubygems'
require 'sinatra'
require 'lib/sinatras-hat'
# Models
require 'post'
require 'comment'
configure do
DataMapper.setup(:default, 'sqlite3:db.sqlite3')
Post.auto_migrate!
Comment.auto_migrate!
Post.create :name => 'A test', :body => "Some sort of thing"
new_post = Post.create :name => 'Another test', :body => "This is some other sort of thing"
new_post.comments.create :body => "A comment"
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/example/lib/comment.rb | example/lib/comment.rb | require 'dm-core'
require 'dm-serializer'
class Comment
include DataMapper::Resource
include DataMapper::Serialize
property :id, Serial, :key => true
property :post_id, Integer
property :body, Text
belongs_to :post
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/example/lib/post.rb | example/lib/post.rb | require 'dm-core'
require 'dm-serializer'
require 'dm-timestamps'
class Post
include DataMapper::Resource
include DataMapper::Serialize
property :id, Serial, :key => true
property :name, String
property :body, Text
property :created_at, DateTime
property :updated_at, DateTime
has n, :comments
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat.rb | lib/sinatras-hat.rb | $LOAD_PATH << File.join(File.dirname(__FILE__))
require 'benchmark'
require 'sinatra/base'
require 'extlib'
require 'core_ext/array'
require 'core_ext/hash'
require 'core_ext/object'
require 'core_ext/module'
require 'sinatras-hat/logger'
require 'sinatras-hat/extendor'
require 'sinatras-hat/authentication'
require 'sinatras-hat/hash_mutator'
require 'sinatras-hat/resource'
require 'sinatras-hat/response'
require 'sinatras-hat/responder'
require 'sinatras-hat/model'
require 'sinatras-hat/router'
require 'sinatras-hat/actions'
require 'sinatras-hat/maker'
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/core_ext/array.rb | lib/core_ext/array.rb | class Array
def extract_options!
last.is_a?(Hash) ? pop : { }
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/core_ext/object.rb | lib/core_ext/object.rb | require 'metaid'
class Object
def tap
yield self
self
end
def with(hash)
hash.each do |key, value|
meta_def(key) { hash[key] } unless respond_to?(key)
meta_def("#{key}=") { |v| hash[key] = v } unless respond_to?("#{key}=")
end
return unless block_given?
result = yield
hash.each do |key, value|
meta_eval { remove_method(key) }
meta_eval { remove_method("#{key}=") }
end
result
end
module InstanceExecHelper; end
include InstanceExecHelper
def instance_exec(*args, &block)
begin
old_critical, Thread.critical = Thread.critical, true
n = 0
n += 1 while respond_to?(mname="__instance_exec#{n}")
InstanceExecHelper.module_eval{ define_method(mname, &block) }
ensure
Thread.critical = old_critical
end
begin
ret = send(mname, *args)
ensure
InstanceExecHelper.module_eval{ remove_method(mname) } rescue nil
end
ret
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/core_ext/module.rb | lib/core_ext/module.rb | class Module
def delegate(*methods)
options = methods.pop
raise ArgumentError, "Delegation needs a target." unless options.is_a?(Hash) && to = options[:to]
methods.each do |method|
module_eval(<<-EOS, "(__DELEGATION__)", 1)
def #{method}(*args, &block)
#{to}.__send__(#{method.inspect}, *args, &block)
end
EOS
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/core_ext/hash.rb | lib/core_ext/hash.rb | class Hash
def make_indifferent!
keys_values = self.dup
replace(Hash.new { |h,k| h[k.to_s] if Symbol === k })
merge!(keys_values)
end
def nest!
new_params = Hash.new.make_indifferent!
each_pair do |full_key, value|
this_param = new_params
split_keys = full_key.to_s.split(/\]\[|\]|\[/)
split_keys.each_index do |index|
break if split_keys.length == index + 1
this_param[split_keys[index]] ||= Hash.new.make_indifferent!
this_param = this_param[split_keys[index]]
end
this_param[split_keys.last] = value
end
clear
replace(new_params)
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/resource.rb | lib/sinatras-hat/resource.rb | module Sinatra
module Hat
# Handles the logic of generating a path for a given resource,
# taking any and all parents into consideration.
class Resource
def initialize(maker)
@maker = maker
end
def path(suffix, record=nil)
records = record ? path_records_for(record) : []
results = resources.inject("") do |memo, maker|
memo += fragment(maker, record)
end
interpolate(clean(results + suffix.dup), records)
end
private
def interpolate(uri, records)
return uri if records.empty?
uri.gsub(/:(\w+)/) { records.pop.to_param }
end
def path_records_for(record)
[record].tap do |parents|
resources.reverse.each do |resource|
parents << resource.model.find_owner(parents.last.attributes)
parents.compact!
parents.uniq!
end
end
end
def fragment(maker, record)
@maker.eql?(maker) ?
"/#{maker.prefix}" :
"/#{maker.prefix}/" + key(maker)
end
def key(maker)
maker.model.foreign_key.inspect
end
def clean(s)
s.downcase!
s.gsub!(%r(/$), '')
s
end
def resources
@maker.parents + [@maker]
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/authentication.rb | lib/sinatras-hat/authentication.rb | # from http://www.gittr.com/index.php/archive/sinatra-basic-authentication-selectively-applied
# adapted by pat nakajima for sinatra's hat
module Sinatra
module Authorization
class ProtectedAction
attr_reader :credentials, :request, :block
def initialize(request, credentials={}, &block)
@credentials, @request, @block = credentials, request, block
end
def check!
unauthorized! unless auth.provided?
bad_request! unless auth.basic?
unauthorized! unless authorize(*auth.credentials)
end
def remote_user
auth.username
end
private
def authorize(username, password)
block.call(username, password)
end
def unauthorized!
request.response.headers['WWW-Authenticate'] = %(Basic realm="#{credentials[:realm]}")
throw :halt, [ 401, 'Authorization Required' ]
end
def bad_request!
throw :halt, [ 400, 'Bad Request' ]
end
def auth
@auth ||= Rack::Auth::Basic::Request.new(request.env)
end
end
module Helpers
def protect!(request)
return if authorized?(request)
guard = ProtectedAction.new(request, credentials, &authenticator)
guard.check!
request.env['REMOTE_USER'] = guard.remote_user
end
def authorized?(request)
request.env['REMOTE_USER']
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/actions.rb | lib/sinatras-hat/actions.rb | module Sinatra
module Hat
# Contains all of the actions that Sinatra's Hat supports.
# Each action states a name, a path, optionally, the HTTP
# verb, then a block which takes a request object, optionally
# loads data using the :finder or :record options, then
# responds, based on whether or not the action was a success
#
# NOTE: only the :create action renders a different :failure
module Actions
def self.included(map)
map.action :destroy, '/:id', :verb => :delete do |request|
record = model.find(request.params) || request.not_found
record.destroy
responder.success(:destroy, request, record)
end
map.action :new, '/new' do |request|
new_record = model.new(request.params)
responder.success(:new, request, new_record)
end
map.action :update, '/:id', :verb => :put do |request|
record = model.update(request.params) || request.not_found
result = record.save ? :success : :failure
responder.send(result, :update, request, record)
end
map.action :edit, '/:id/edit' do |request|
record = model.find(request.params) || request.not_found
responder.success(:edit, request, record)
end
map.action :show, '/:id' do |request|
record = model.find(request.params) || request.not_found
set_cache_headers(request, record) unless protected?(:show)
responder.success(:show, request, record)
end
map.action :create, '/', :verb => :post do |request|
record = model.new(request.params)
result = record.save ? :success : :failure
responder.send(result, :create, request, record)
end
map.action :index, '/' do |request|
records = model.all(request.params)
set_cache_headers(request, records) unless protected?(:index)
responder.success(:index, request, records)
end
private
def set_cache_headers(request, data)
set_etag(request, data)
set_last_modified(request, data)
end
def set_etag(request, data)
record = model.find_last_modified(Array(data))
return unless record.respond_to?(:updated_at)
request.etag("#{record.id}-#{record.updated_at}-#{data.is_a?(Array)}")
end
def set_last_modified(request, data)
record = model.find_last_modified(Array(data))
return unless record.respond_to?(:updated_at)
request.last_modified(record.updated_at)
end
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/logger.rb | lib/sinatras-hat/logger.rb | module Sinatra
module Hat
# TODO This needs to be using Rack::CommonLogger
class Logger
def initialize(maker)
@maker = maker
end
def info(msg)
say msg
end
def debug(msg)
say msg
end
def warn(msg)
say msg
end
def error(msg)
say msg
end
def fatal(msg)
say msg
end
private
def say(msg)
puts msg if @maker.app and @maker.app.logging
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/hash_mutator.rb | lib/sinatras-hat/hash_mutator.rb | module Sinatra
module Hat
# Used for specifying custom responses using a corny DSL.
class HashMutator
def initialize(hash)
@hash = hash
end
def success(&block)
@hash[:success] = block
end
def failure(&block)
@hash[:failure] = block
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/responder.rb | lib/sinatras-hat/responder.rb | module Sinatra
module Hat
# The responder assigns data to instance variables, then either
# gets the appropriate response proc and instance_exec's it in the
# context of a new Response object, or serializes the data.
class Responder
delegate :model, :to => :maker
attr_reader :maker
def initialize(maker)
@maker = maker
end
def defaults
@defaults ||= {
:show => {
:success => proc { |data| render(:show) },
:failure => proc { |data| redirect('/') }
},
:index => {
:success => proc { |data| render(:index) },
:failure => proc { |data| redirect('/') }
},
:create => {
:success => proc { |data| redirect(data) },
:failure => proc { |data| render(:new) }
},
:new => {
:success => proc { |data| render(:new) },
:failure => proc { |data| redirect('/') }
},
:edit => {
:success => proc { |data| render(:edit) }
},
:destroy => {
:success => proc { |data| redirect(resource_path('/')) }
},
:update => {
:success => proc { |data| redirect(data) },
:failure => proc { |data| render(:edit) }
}
}
end
# Called when a request is handled successfully. For most GET
# requests, this is always the case. For update/create actions,
# it is when the record is created/updated successfully.
def success(name, request, data)
handle(:success, name, request, data)
end
# Called when a request is not able to handled. This could be
# because a record could not be created or saved.
def failure(name, request, data)
handle(:failure, name, request, data)
end
# Serializes the data passed in, first looking for a custom formatter,
# then falling back on trying to call to_[format] on the data. If neither
# are available, returns an error with the status code 406.
def serialize(data, format)
return nil unless format
name = format.to_sym
mime = get_mime_type(format)
formatter = to_format(name)
formatter[data] ? [formatter[data], mime] : nil
end
private
def handle(result, name, request, data)
if format = request.params[:format] || maker.format
response, mime = serialize(data, format)
request.content_type(mime) if mime
response or request.error(406)
else
request.instance_variable_set(ivar_name(data), data)
response = Response.new(maker, request)
response.instance_exec(data, &defaults[name][result])
end
end
def get_mime_type(format)
Rack::Mime::MIME_TYPES['.' + format.to_s]
end
def ivar_name(data)
"@" + (data.kind_of?(Array) ? model.plural : model.singular)
end
def to_format(name)
maker.formats[name] || Proc.new do |data|
method_name = "to_#{name}"
data.respond_to?(method_name) ? data.send(method_name) : nil
end
end
end
end
end
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/maker.rb | lib/sinatras-hat/maker.rb | module Sinatra
module Hat
# This is where it all comes together
class Maker
include Sinatra::Hat::Extendor
include Sinatra::Authorization::Helpers
attr_reader :klass, :app
def self.actions
@actions ||= { }
end
def self.action(name, path, options={}, &block)
verb = options[:verb] || :get
Router.cache << [verb, name, path]
actions[name] = { :path => path, :verb => verb, :fn => block }
end
def self.option_setter(name, options={})
setter = options[:collection] ? 'Set.new(args)' : 'args.first'
class_eval(<<-END, __FILE__, __LINE__)
def #{name}(*args, &block)
return options[#{name.inspect}] = block if block_given?
return options[#{name.inspect}] = #{setter} unless args.empty?
return options[#{name.inspect}]
end
END
end
include Sinatra::Hat::Actions
# ======================================================
# The finder block is used when loading all records for the index
# action. It gets passed the model proxy and the request params hash.
option_setter :finder
# The finder block is used when loading a single record, which
# is the case for most actions. It gets passed the model proxy
# and the request params hash.
option_setter :record
# The authenticator block gets called before protected actions. It
# gets passed the basic auth username and password.
option_setter :authenticator
# A list of actions that get generated by this maker instance. By
# default it's all of the actions specified in actions.rb
option_setter :only, :collection => true
# A way to determine a record's representation in the database
option_setter :to_param
# The path prefix to use for generating groutes.
option_setter :prefix
option_setter :format
def initialize(klass, overrides={})
@klass = klass
options.merge!(overrides)
with(options)
end
# Simply stores the app instance when #mount is called.
def setup(app)
@app = app
end
# Processes a request, using the action specified in actions.rb
#
# TODO The work of handling a request should probably be wrapped
# up in a class.
def handle(action, request)
request.error(404) unless only.include?(action)
protect!(request) if protect.include?(action)
log_with_benchmark(request, action) do
instance_exec(request, &self.class.actions[action][:fn])
end
end
# Allows the DSL for specifying custom flow controls in a #mount
# block by altering the responder's defaults hash.
def after(action)
yield HashMutator.new(responder.defaults[action])
end
# A list of actions to protect via basic auth. Protected actions
# will have the authenticator block called before they are handled.
def protect(*actions)
credentials.merge!(actions.extract_options!)
if actions.empty?
options[:protect] ||= Set.new([])
else
actions == [:all] ?
Set.new(options[:protect] = only) :
Set.new(options[:protect] = actions)
end
end
# An array of parent Maker instances under which this instance
# was nested.
def parents
@parents ||= parent ? parent.parents + Array(parent) : []
end
# Looks up the resource path for the specified arguments using this
# maker's Resource instance.
def resource_path(*args)
resource.path(*args)
end
# Default options
def options
@options ||= {
:only => Set.new(Maker.actions.keys),
:parent => nil,
:format => nil,
:prefix => model.plural,
:finder => proc { |model, params| model.all },
:record => proc { |model, params| model.send("find_by_#{to_param}", params[:id]) },
:protect => [ ],
:formats => { },
:to_param => :id,
:credentials => { :username => 'username', :password => 'password', :realm => "The App" },
:authenticator => proc { |username, password| [username, password] == [:username, :password].map(&credentials.method(:[])) }
}
end
# Generates routes in the context of the given app.
def generate_routes!
Router.new(self).generate(@app)
end
# The responder determines what kind of response should used for
# a given action.
#
# TODO It might be better off to instantiate a new one of these per
# request, instead of having one per maker instance.
def responder
@responder ||= Responder.new(self)
end
# Handles ORM/model related logic.
def model
@model ||= Model.new(self)
end
# TODO Hook this into Rack::CommonLogger
def logger
@logger ||= Logger.new(self)
end
private
# Generates paths for this maker instance.
def resource
@resource ||= Resource.new(self)
end
def protected?(action)
protect.include?(action)
end
# Handles a request with logging and benchmarking.
def log_with_benchmark(request, action)
msg = [ ]
msg << "#{request.env['REQUEST_METHOD']} #{request.env['PATH_INFO']}"
msg << "Params: #{request.params.inspect}"
msg << "Action: #{action.to_s.upcase}"
logger.info "[sinatras-hat] " + msg.join(' | ')
result = nil
t = Benchmark.realtime { result = yield }
logger.info " Request finished in #{t} sec."
result
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/response.rb | lib/sinatras-hat/response.rb | module Sinatra
class NoTemplateError < StandardError; end
module Hat
# Tells Sinatra what to do next.
class Response
attr_reader :maker
delegate :model, :resource_path, :to => :maker
def initialize(maker, request)
@maker = maker
@request = request
end
def render(action, options={})
begin
options.each { |sym, value| @request.send(sym, value) }
@request.erb "#{maker.prefix}/#{action}".to_sym
rescue Errno::ENOENT
no_template! "Can't find #{File.expand_path(File.join(views, action.to_s))}.erb"
end
end
def redirect(*args)
@request.redirect url_for(*args)
end
def url_for(resource, *args)
case resource
when String then resource
when Symbol then resource_path(Maker.actions[resource][:path], *args)
else maker_for(resource).resource_path('/:id', resource)
end
end
private
def no_template!(msg)
raise NoTemplateError.new(msg)
end
def views
@views ||= begin
if views_dir = @request.options.views
File.join(views_dir, maker.prefix)
else
no_template! "Make sure you set the :views option!"
end
end
end
def maker_for(record)
resource = record.is_a?(model.klass) ? maker : maker.parents.detect { |m| record.is_a?(m.model.klass) }
resource || maker
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/router.rb | lib/sinatras-hat/router.rb | module Sinatra
module Hat
# Tells Sinatra which routes to generate. The routes
# created automatically when the actions are loaded.
class Router
delegate :resource_path, :logger, :to => :maker
attr_reader :maker, :app
def self.cache
@cache ||= []
end
def initialize(maker)
@maker = maker
end
def generate(app)
@app = app
Router.cache.each do |route|
map(*route)
end
end
private
def map(method, action, path)
path = resource_path(path)
handler = lambda do |request|
maker.handle(action, request)
end
logger.info ">> route for #{maker.klass} #{action}:\t#{method.to_s.upcase}\t#{path}"
app.send(method, "#{path}*" + "/?") do
id, format = (params[:id].to_s + params[:splat].join).split('.')
params['id'] = id
params['format'] = format
handler[self]
end
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/extendor.rb | lib/sinatras-hat/extendor.rb | module Sinatra
module Hat
# This module gives both Sinatra::Base and Sinatra::Hat::Maker
# the #mount method, which is used to mount resources. When
# mount is called in an instance of Maker, it sets the new
# instance's parent.
module Extendor
def mount(klass, options={}, &block)
unless kind_of?(Sinatra::Hat::Maker)
use Rack::MethodOverride
end
Maker.new(klass, options).tap do |maker|
maker.parent = self if kind_of?(Sinatra::Hat::Maker)
maker.setup(@app || self)
maker.instance_eval(&block) if block_given?
maker.generate_routes!
end
end
end
end
end
Sinatra::Base.extend(Sinatra::Hat::Extendor)
| ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
nakajima/sinatras-hat | https://github.com/nakajima/sinatras-hat/blob/e2ee15d57bb6831af4769c94ce01604e0546c1d6/lib/sinatras-hat/model.rb | lib/sinatras-hat/model.rb | module Sinatra
module Hat
# A wrapper around the model class that we're mounting
class Model
attr_reader :maker
delegate :options, :klass, :prefix, :to => :maker
def initialize(maker)
@maker = maker
end
# Loads all records using the maker's :finder option.
def all(params)
params.make_indifferent!
options[:finder].call(proxy(params), params)
end
# Loads one record using the maker's :record option.
def find(params)
params.make_indifferent!
options[:record].call(proxy(params), params)
end
# Finds the owner record of a nested resource.
def find_owner(params)
params = parent_params(params)
options[:record].call(proxy(params), params)
end
# Updates a record with the given params.
def update(params)
if record = find(params)
params.nest!
record.attributes = (params[singular] || { })
record
end
end
# Returns a new instance of the mounted model.
def new(params={})
params.nest!
proxy(params).new(params[singular] || { })
end
# Returns the pluralized name for the model.
def plural
klass.name.snake_case.plural
end
# Returns the singularized name for the model.
def singular
klass.name.snake_case.singular
end
# Returns the foreign_key to be used for this model.
def foreign_key
"#{singular}_id".to_sym
end
# Returns the last modified record from the array of records
# passed in. It's thorougly inefficient, since it requires all
# of the cacheable data to be loaded anyway.
def find_last_modified(records)
if records.all? { |r| r.respond_to?(:updated_at) }
records.sort_by { |r| r.updated_at }.last
else
records.last
end
end
private
# Returns an association proxy for a nested resource if available,
# otherwise it just returns the class.
def proxy(params)
return klass unless parent
owner = parent.find_owner(params)
if owner and owner.respond_to?(plural)
owner.send(plural)
else
klass
end
end
# Dups and modifies params so that they can be used to find a parent.
def parent_params(params)
_params = params.dup.to_mash
_params.merge! :id => _params.delete(foreign_key)
_params
end
# Returns the parent model if there is one, otherwise nil.
def parent
return nil unless maker.parent
maker.parent.model
end
end
end
end | ruby | MIT | e2ee15d57bb6831af4769c94ce01604e0546c1d6 | 2026-01-04T17:43:56.302326Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/benchmark/update_event.rb | benchmark/update_event.rb | require "perftools"
require "benchmark"
require "logger"
require "chronologic"
Chronologic.connection = Cassandra.new("ChronologicTest")
# logger = Logger.new(STDOUT)
# logger.level = Logger::DEBUG
# Chronologic::Service::Schema.logger = logger
protocol = Chronologic::Service::Protocol
subscriber_count = Integer(ARGV.first)
event_count = Integer(ARGV.last)
start = Time.now.tv_sec
result = Benchmark.measure do
first_timeline = "update_events_bench_0"
other_timeline = "update_events_bench_1"
events = []
subscriber_count.times do |n|
protocol.subscribe("ue_sink_#{n}", first_timeline)
protocol.subscribe("ue_sink_#{n}", other_timeline)
end
event_create = Benchmark.measure do
events = event_count.times.map do |n|
event = Chronologic::Event.new(
"key" => "ue_event_#{start}_#{n}",
"data" => {"blah" => "This is #{n}"},
"objects" => {},
"timelines" => [first_timeline]
)
protocol.publish(event)
event
end
end
puts "%.5fs/publish" % [event_create.total/event_count]
puts "#{event_create.total}s total"
# Create n events
event_update = Benchmark.measure do
PerfTools::CpuProfiler.start("tmp/update_events_after_#{subscriber_count}_#{event_count}") do
events.each do |event|
event.timelines = [first_timeline, other_timeline]
protocol.update_event(event, true)
end
end
end
puts "%.5fs/update_event" % [event_update.total/event_count]
puts "#{event_update.total}s total"
end
puts "#{result.total}s total"
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/benchmark/objectless_feed.rb | benchmark/objectless_feed.rb | require 'chronologic'
require 'benchmark'
n_events = 100
# n_objects = rand(10)
n_objects = 20
n_feeds = 1000
Chronologic.connection = Cassandra.new('Chronologic')
protocol = Chronologic::Service::Protocol
timestamp = Time.now.tv_sec
timeline = ['objectless', timestamp].join('-')
puts "Benchmarking for #{timeline}"
puts Benchmark.measure {
n_events.times do |i|
objects = n_objects.times.map do |n|
key = ['object', timestamp, n].join('-')
data = {'value' => 'b' * 512}
protocol.record(key, data)
key
end
event = Chronologic::Event.new(
:key => ['objectless', timestamp, i].join('-'),
:data => {'foo' => 'a' * 768},
:objects => {'things' => objects},
:timelines => [timeline]
)
protocol.publish(event)
end
}
Benchmark.bmbm(20) do |x|
x.report("feed") do
n_feeds.times { protocol.feed(timeline, :per_page => 20).items }
end
x.report("objectless") do
n_feeds.times { protocol.feed(timeline, :per_page => 20, :strategy => "objectless").items }
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/benchmark/publish.rb | benchmark/publish.rb | # $ ruby -rubygems -Ilib benchmark/publish.rb
require "perftools"
require "benchmark"
require "chronologic"
def create_friendship(timeline, subscriber)
Chronologic::Protocol.subscribe(timeline, subscriber)
end
def create_event(key, timeline)
ev = Chronologic::Event.new
ev.key = key
ev.timestamp = Time.now
ev.data = {"test" => true}
ev.objects = {}
ev.timelines = [timeline]
Chronologic::Protocol.publish(ev)
end
def dump_results(data)
flat = File.expand_path(File.dirname(__FILE__) + "publish_flat.txt")
graph = File.expand_path(File.dirname(__FILE__) + "publish_graph.html")
RubyProf::FlatPrinter.new(data).print(File.open(flat, "w"), 1)
RubyProf::GraphHtmlPrinter.new(data).print(File.open(graph, "w"))
end
friends = 50
events = 1000
timeline = "cl_timeline"
Chronologic.connection = Cassandra.new("ChronologicTest")
if __FILE__ == $PROGRAM_NAME
result = Benchmark.measure do
friends.times { |i| create_friendship("cl_subscriber_#{i}", timeline) }
end
puts "%.5fms/subscribe" % [friends/result.total]
result = Benchmark.measure do
PerfTools::CpuProfiler.start("tmp/publish_profile") do
events.times { |i| create_event("cl_event_#{i}", timeline) }
end
end
puts "%.5fms/publish" % [events/result.total]
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/benchmark/timeline_client.rb | benchmark/timeline_client.rb | # $ ruby -rubygems -Ilib benchmark/publish.rb
require "benchmark"
require "chronologic"
iterations = Integer(ARGV.last)
timelines = [1, 2, 3, 4, 5, 6, 3104, 1699].map { |id| ["user_#{id}", "user_#{id}_home"] }.flatten
# cl = Chronologic::Client.new("http://localhost:7979")
cl = Chronologic::Client.new('https://api.gowalla.com/services/chronologic')
if __FILE__ == $PROGRAM_NAME
result = Benchmark.measure do
iterations.times do
feed = timelines.shuffle.first
cl.timeline(feed, :subevents => true)
end
end
puts "%.5fs/timeline" % [result.total/iterations]
puts "#{result.real}s total"
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/benchmark/timeline.rb | benchmark/timeline.rb | # $ ruby -rubygems -Ilib benchmark/publish.rb
require "perftools"
require "benchmark"
require "logger"
require "chronologic"
servers = [
'10.250.203.127:9160',
'10.210.13.171:9160',
'10.250.227.63:9160',
'10.250.230.111:9160'
]
Chronologic.connection = Cassandra.new(
"ChronologicTest",
servers,
:retries => 3
)
# logger = Logger.new(STDOUT)
# logger.level = Logger::DEBUG
# Chronologic::Schema.logger = logger
iterations = Integer(ARGV.last)
timelines = [1, 2, 3, 4, 5, 6, 3104, 1699].map { |id| ["user_#{id}", "user_#{id}_home"] }.flatten
if __FILE__ == $PROGRAM_NAME
result = Benchmark.measure do
PerfTools::CpuProfiler.start("tmp/timeline_profile") do
iterations.times do
feed = timelines.shuffle.first
Chronologic::Protocol.feed(feed, :fetch_subevents => true).items
end
end
end
puts "%.5fs/timeline" % [result.total/iterations]
puts "#{result.total}s total"
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic_spec.rb | spec/chronologic_spec.rb | require 'spec_helper'
describe Chronologic do
it "holds a Cassandra connection" do
fake_connection = Object.new
Chronologic.connection = fake_connection
Chronologic.connection.should eq(fake_connection)
end
it "has a schema helper" do
Chronologic.schema.should eq(Chronologic::Service::Schema)
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/helpers.rb | spec/helpers.rb | module ChronologicHelpers
def simple_event(kind=:service)
case kind
when :service
Chronologic::Service::Event.new.tap do |event|
event.key = "checkin_1"
event.data = {"type" => "checkin", "message" => "I'm here!"}
event.objects = {"user" => "user_1", "spot" => "spot_1"}
event.timelines = ["user_1", "spot_1"]
end
when :client
Chronologic::Client::Event.new.tap do |event|
event.key = "checkin_1"
event.data = {"type" => "checkin", "message" => "I'm here!"}
event.objects = {"user" => "user_1", "spot" => "spot_1"}
event.timelines = ["user_1", "spot_1"]
end
else
raise ArgumentError.new("Unknown event: #{kind}")
end
end
def nested_event
Chronologic::Service::Event.new.tap do |event|
event.key = "comment_1"
event.data = {"type" => "comment", "message" => "Me too!", "parent" => "checkin_1"}
event.objects = {"user" => "user_2"}
event.timelines = ["checkin_1"]
end
end
def populate_timeline
jp = {"name" => "Juan Pelota's"}
protocol.record("spot_1", jp)
events = []
%w{sco jc am pb mt rm ak ad rs bf}.each_with_index do |u, i|
record = {"name" => u}
key = "user_#{i}"
protocol.record(key, record)
protocol.subscribe("user_1_home", "user_#{i}")
event = simple_event
event.key = "checkin_#{i}"
event.objects["user"] = key
event.timelines = [key, "spot_1"]
events << event
protocol.publish(event)
end
return events
end
# Cassandra#truncate isn't reliable against cassandra-0.7.4, but
# this gets the job done. It's a hack, so look for a better way to do this
# every now and then
def clean_up_keyspace!(conn)
conn.schema.cf_defs.each do |cf|
conn.send(:each_key, cf.name) do |k|
conn.remove(cf.name, k)
end
end
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/functional_helper.rb | spec/functional_helper.rb | require 'cassandra/0.7'
require 'chronologic'
require 'rack/test'
require 'helpers'
MultiJson.engine = :yajl
module FunctionalTestHelpers
def self.truncate_cfs
c = Cassandra.new("ChronologicTest")
[:Object, :Subscription, :Timeline, :Event].each do |cf|
c.truncate!(cf)
end
end
def truncate_cfs
FunctionalTestHelpers.truncate_cfs
end
# AKK Could this move into an RSpec let?
def connection
@connection ||= Chronologic::Client::Connection.new('http://localhost:7979')
end
end
RSpec.configure do |config|
config.include ChronologicHelpers
config.include(FunctionalTestHelpers)
config.before { FunctionalTestHelpers.truncate_cfs }
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/spec_helper.rb | spec/spec_helper.rb | require 'chronologic'
require 'webmock/rspec'
require 'cassandra/0.7'
require 'cassandra/mock'
require 'helpers'
MultiJson.engine = :yajl
RSpec.configure do |config|
config.include(ChronologicHelpers)
config.include(WebMock::API)
config.before do
if ENV['CASSANDRA']
Chronologic::Service::Schema.write_opts = {
:consistency => Cassandra::Consistency::ONE
}
Chronologic.connection = Cassandra.new(
'ChronologicTest',
['127.0.0.1:9160'],
:connection_timeout => 3,
:retries => 2,
:timeout => 3
)
clean_up_keyspace!(Chronologic.connection)
else
schema = {
'ChronologicTest' => {
'Object' => {},
'Subscription' => {},
'Event' => {},
'Timeline' => {}
}
}
Chronologic.connection = Cassandra::Mock.new('ChronologicTest', schema)
end
end
config.before do
WebMock.disable_net_connect!
WebMock.reset!
end
end
shared_examples "a feed strategy" do
it "fetches a timeline" do
length = populate_timeline.length
subject.create("user_1_home").items.length.should == length
end
it "generates a feed and properly handles empty subevents" do
event = simple_event
protocol.publish(event)
feed = subject.create(
event.timelines.first,
:fetch_subevents => true
)
feed.items.first.subevents.should == []
end
it "fetches a feed by page" do
populate_timeline
page = subject.create("user_1_home", :per_page => 5).next_page
subject.create(
"user_1_home",
:page => page,
:per_page => 5
).items.length.should ==(5)
end
# AKK: it would be great if we didn't have to call feed.items to load
# the paging bits
it "tracks the event key for the next page" do
populate_timeline
feed = subject.new("user_1_home", 1)
feed.items
feed.next_page.should_not be_nil
end
it "doesn't set the next page if there is no next page" do
events = populate_timeline
feed = subject.new("user_1_home", events.length)
feed.items
feed.next_page.should be_nil
end
it "stores the item count for the feed" do
pending("Cheating on counts for a while")
events = populate_timeline
feed = subject.new("user_1_home")
feed.items
feed.count.should == events.length
end
it "fetches multiple objects per type" do
protocol.record("user_1", {"name" => "akk"})
protocol.record("user_2", {"name" => "bf"})
event = simple_event
event.objects["test"] = ["user_1", "user_2"]
protocol.publish(event)
feed = subject.create(event.timelines.first)
feed.items.first.objects["test"].length.should == 2
end
it "fetches two levels of subevents" do
pending("Cheating on sub-subevents for now")
grouping = simple_event
grouping.key = "grouping_1"
grouping['data'] = {"grouping" => "flight"}
grouping.timelines = ["subsubevent_test"]
event = simple_event
event.parent = grouping.key
event.timelines = [grouping.key]
subevent = simple_event
subevent.key = "comment_1"
subevent.parent = event.key
subevent['data']['type'] = "comment"
subevent['data']['message'] = "Great!"
subevent.timelines = [event.key]
protocol.publish(grouping)
protocol.publish(event)
protocol.publish(subevent)
feed = subject.new("subsubevent_test", 20, nil, true)
feed.items.first.
subevents.first.
subevents.first.key.should == subevent.key
end
end
shared_examples_for "a CL event" do
let(:nested_event) do
described_class.from_attributes(
:key => "comment_1",
:data => {"type" => "comment", "message" => "Me too!", "parent" => "checkin_1"},
:objects => {"user" => "user_2"},
:timelines => ["checkin_1"]
)
end
it "knows whether it is a subevent" do
nested_event.subevent?.should == true
end
it "knows its parent event" do
nested_event.parent.should == "checkin_1"
end
it "sets its parent event" do
event = nested_event
event.parent = "highlight_1"
event.parent.should == "highlight_1"
end
it "returns children as CL::Event objects" do
subevent = {
"key" => "bar_1",
"data" => {"bar" => "herp"}
}
event = described_class.from_attributes(
:key => "foo_1",
:data => {"foo" => "derp"},
:subevents => [subevent]
)
event.children.should eq([described_class.from_attributes(subevent)])
end
it "flags an empty event" do
subject.data = {}
subject.should be_empty
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/service/schema_spec.rb | spec/chronologic/service/schema_spec.rb | require 'spec_helper'
describe Chronologic::Service::Schema do
let(:protocol) { Chronologic::Service::Protocol }
before do
@schema = Chronologic::Service::Schema
end
it "creates an object" do
attrs = {"name" => "akk"}
@schema.create_object("user_1", attrs)
@schema.object_for("user_1").should == attrs
end
it "fetches multiple objects" do
akk = {"name" => "akk"}
sco = {"name" => "sco"}
@schema.create_object("user_1", akk)
@schema.create_object("user_2", sco)
hsh = {"user_1" => akk, "user_2" => sco}
@schema.object_for(["user_1", "user_2"]).should == hsh
end
it "doesn't fetch an empty array of objects" do
raise_on_multiget
@schema.object_for([]).should == Hash.new
end
it "removes an object" do
@schema.create_object("user_1", {"name" => "akk"})
@schema.remove_object("user_1")
@schema.object_for("user_1").should == Hash.new
end
it "creates a subscription" do
@schema.create_subscription("user_1_home", "user_2")
@schema.subscribers_for("user_2").should == ["user_1_home"]
end
it 'creates a subscription with backlinks' do
@schema.create_subscription('user_1_home', 'user_2', 'user_1')
@schema.followers_for('user_2').should == ['user_1']
end
it "fetches multiple subscriptions" do
@schema.create_subscription("user_1_home", "user_2")
@schema.create_subscription("user_2_home", "user_1")
@schema.subscribers_for(["user_1", "user_2"]).should include("user_1_home")
@schema.subscribers_for(["user_1", "user_2"]).should include("user_2_home")
end
it "doesn't fetch an empty array of subscriptions" do
raise_on_multiget
@schema.subscribers_for([]).should == Array.new
end
it "removes a subscription" do
@schema.create_subscription("user_1", "user_2")
@schema.remove_subscription("user_1", "user_2")
@schema.subscribers_for("user_1").should == []
end
it 'checks whether a feed is connected to a timeline' do
@schema.create_subscription('user_1_home', 'user_2', 'user_1')
@schema.create_subscription('user_3_home', 'user_2', 'user_3')
@schema.followers_for('user_2').should == ['user_1', 'user_3']
end
it 'checks whether a feed is not connected to a timeline' do
@schema.create_subscription('user_1_home', 'user_2', 'user_1')
@schema.followers_for('user_1').should == []
end
it "checks the existence of an event" do
@schema.create_event("checkin_1111", simple_data)
@schema.event_exists?("checkin_1111").should be_true
end
it "creates an event" do
data = simple_data
@schema.create_event("checkin_1111", data)
@schema.event_for("checkin_1111").should == data
end
it "fetches multiple events" do
data = simple_data
@schema.create_event("checkin_1111", data)
@schema.create_event("checkin_1112", data)
@schema.event_for(["checkin_1111", "checkin_1112"]).should == {"checkin_1111" => data, "checkin_1112" => data}
end
it "does not fetch an empty array of events" do
raise_on_multiget
@schema.event_for([]).should == Hash.new
end
it "iterates over events" do
keys = ["checkin_1111", "checkin_2222", "checkin_3333"]
keys.each { |k| @schema.create_event(k, simple_data) }
event_keys = []
@schema.each_event do |key, event|
event_keys << key
event.should eq(simple_data)
end
event_keys.should eq(keys)
end
it "iterates over events, starting from a key" do
keys = ["checkin_1111", "checkin_2222", "checkin_3333"]
keys.each { |k| @schema.create_event(k, simple_data) }
event_keys = []
@schema.each_event('checkin_2222') do |key, event|
event_keys << key
event.should eq(simple_data)
end
event_keys.should have(2).items
end
it "removes an event" do
@schema.create_event("checkin_1111", simple_data)
@schema.remove_event("checkin_1111")
@schema.event_for("checkin_1111").should == Hash.new
end
it "updates an event" do
data = simple_data
@schema.create_event("checkin_1111", data)
data["hotness"] = "So new!"
@schema.update_event("checkin_1111", data)
@schema.event_for("checkin_1111").should eq(data)
end
it "creates a new timeline event" do
key = "gizmo_1111"
token = [Time.now.tv_sec, key].join('_')
data = {"gizmo" => MultiJson.encode({"message" => "I'm here!"})}
@schema.create_event(key, data)
@schema.create_timeline_event("_global", token, key)
@schema.timeline_for("_global").should ==({token => key})
@schema.timeline_events_for("_global").values.should == [key]
end
it "creates timeline events without duplicates if timestamps match" do
key = "gizmo_1111"
token = [Time.now.tv_sec, key].join('_')
@schema.create_timeline_event("_global", token, key)
@schema.create_timeline_event("_global", token, key)
@schema.timeline_events_for("_global").length.should == 1
end
it "fetches timeline events with a count parameter" do
tokens = 15.times.inject({}) { |result, i|
key = "gizmo_#{i}"
token = [Time.now.tv_sec, key].join('_')
@schema.create_timeline_event("_global", token, key)
result.update(token => key)
}.sort_by { |token, key| token }
events = @schema.timeline_for("_global", :per_page => 10)
events.length.should == 10
events.sort_by { |token, key| token }.should == tokens.slice(5, 10)
end
it "fetches timeline events from a page offset" do
pending('rewrite to work with real cassandra and mocked cassandra')
uuids = 15.times.map { @schema.new_guid }.reverse
uuids.each_with_index do |uuid, i|
ref = "gizmo_#{i}"
@schema.create_timeline_event("_global", uuid, ref)
end
offset = uuids[10]
@schema.timeline_for("_global", :page => offset).length.should == 5
end
it "fetches timeline events with a count and offset parameter" do
pending('rewrite to work with real cassandra and mocked cassandra')
uuids = 15.times.map { @schema.new_guid }
uuids.each_with_index do |uuid, i|
ref = "gizmo_#{i}"
@schema.create_timeline_event("_global", uuid, ref)
end
@schema.timeline_for("_global", :per_page => 10, :page => uuids[11]).length.should == 10
@schema.timeline_for("_global", :per_page => 10, :page => uuids[4]).length.should == 5#, "doesn't truncate when length(count+offset) > length(results)"
end
it "does not fetch an empty array of timelines" do
raise_on_multiget
@schema.timeline_for([]).should == Hash.new
end
it "fetches an extra item when a page parameter is specified and truncates appropriately" do
pending('rewrite to work with real cassandra and mocked cassandra')
uuids = 15.times.inject({}) { |result, i|
uuid = @schema.new_guid
ref = "gizmo_#{i}"
@schema.create_timeline_event("_global", uuid, ref)
result.update(uuid => ref)
}.sort_by { |uuid, ref| uuid }
start = uuids[10][0]
events = @schema.timeline_for(
"_global",
:per_page => 5,
:page => start
)
events.length.should == 5
events.sort_by { |uuid, ref| uuid }.should == uuids.slice(5, 5)
end
it "removes a timeline event" do
data = simple_data
key = "gizmo_1111"
token = [Time.now.tv_sec, key].join("_")
@schema.create_event("gizmo_1111", data)
@schema.create_timeline_event("_global", token, key)
@schema.remove_timeline_event("_global", token)
@schema.timeline_events_for("_global").values.should == []
end
it "counts items in a timeline" do
pending("Cheating on counts for a while")
10.times { |i| @schema.create_timeline_event("_global", i.to_s, "junk") }
@schema.timeline_count("_global").should == 10
end
it "fetches events for one or more timelines" do
events = [simple_event]
events << simple_event.tap do |e|
e.key = "checkin_2"
e.data['message'] = "I'm over there!"
end
events << simple_event.tap do |e|
e.key = "checkin_3"
e.data['message'] = "I'm way over there!"
end
events << simple_event.tap do |e|
e.key = "checkin_4"
e.data['message'] = "I'm over here!"
e.timelines = ["user_2"]
end
events << simple_event.tap do |e|
e.key = "checkin_5"
e.data['message'] = "I'm nowhere!"
e.timelines = ["user_2"]
end
events.each { |e| protocol.publish(e) }
events = subject.fetch_timelines(["user_1", "user_2"])
events.length.should == 5
events.each { |e| e.should be_instance_of(Chronologic::Service::Event) }
end
it "fetches objects associated with an event" do
protocol.record("spot_1", {"name" => "Juan Pelota's"})
protocol.record("user_1", {"name" => "akk"})
protocol.record("user_2", {"name" => "bf"})
event = simple_event
event.objects["test"] = ["user_1", "user_2"]
populated_event = subject.fetch_objects([event]).first
populated_event.objects["test"].length.should == 2
populated_event.objects["user"].should be_kind_of(Hash)
populated_event.objects["spot"].should be_kind_of(Hash)
end
describe "feed reification" do
it "constructs a feed from multiple events" do
events = 5.times.map { simple_event }
timeline = subject.reify_timeline(events)
timeline.length.should == 5
end
it "constructs a feed from events with subevents" do
events = [simple_event, nested_event]
timeline = subject.reify_timeline(events)
timeline.length.should == 1
timeline.first.subevents.should == [events.last]
end
it "constructs a feed from events with sub-subevents" do
events = [simple_event, nested_event]
events << simple_event.tap do |e|
e.key = "checkin_2"
e.data['message'] = "I'm over there"
end
events << simple_event.tap { |e| e.key = "grouping_1" }
events << simple_event.tap do |e|
e.key = "checkin_3"
e.parent = "grouping_1"
e.timelines << "grouping_1"
end
events << simple_event.tap do |e|
e.key = "comment_2"
e.parent = "checkin_3"
e.timelines << "checkin_3"
end
timeline = subject.reify_timeline(events)
timeline.length.should == 3
timeline[0].subevents.length.should == 1
timeline[1].subevents.length.should == 0
timeline[2].subevents.length.should == 1
timeline[2].subevents[0].subevents.length.should == 1
end
end
def simple_data
{"checkin" => MultiJson.encode({"message" => "I'm here!"})}
end
def raise_on_multiget
double = Object.new
class <<double
def multi_get(*args)
raise "multi_get should not get called"
end
end
Chronologic.connection = double
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/service/objectless_feed_spec.rb | spec/chronologic/service/objectless_feed_spec.rb | require 'spec_helper'
describe Chronologic::Service::ObjectlessFeed do
let(:protocol) { Chronologic::Service::Protocol }
subject { Chronologic::Service::ObjectlessFeed }
it_behaves_like "a feed strategy"
# AKK: reduce duplication of code in this examples
it "generates a feed for a timeline key" do
akk = {"name" => "akk"}
jp = {"name" => "Juan Pelota's"}
protocol.record("user_1", akk)
protocol.record("spot_1", jp)
event = simple_event
protocol.subscribe("user_1_home", "user_1")
protocol.publish(event)
["user_1", "spot_1", "user_1_home"].each do |t|
feed = subject.create(t).items
feed[0].data.should == event.data
end
end
# AKK: reduce duplication of code in this examples
it "generates a feed for a timeline key, fetching nested timelines" do
akk = {"name" => "akk"}
sco = {"name" => "sco"}
jp = {"name" => "Juan Pelota's"}
protocol.record("user_1", akk)
protocol.record("user_2", sco)
protocol.record("spot_1", jp)
event = Chronologic::Service::Event.new
event.key = "checkin_1111"
event.data = {"type" => "checkin", "message" => "I'm here!"}
event.objects = {"user" => "user_1", "spot" => "spot_1"}
event.timelines = ["user_1", "spot_1"]
protocol.subscribe("user_1_home", "user_1")
event = protocol.publish(event)
event = Chronologic::Service::Event.new
event.key = "comment_1111"
event.data = {"type" => "comment", "message" => "Me too!", "parent" => "checkin_1111"}
event.objects = {"user" => "user_2"}
event.timelines = ["checkin_1111"]
protocol.publish(event)
event = Chronologic::Service::Event.new
event.key = "comment_2222"
event.data = {"type" => "comment", "message" => "Great!", "parent" => "checkin_1111"}
event.objects = {"user" => "user_1"}
event.timelines = ["checkin_1111"]
protocol.publish(event)
protocol.schema.timeline_events_for("checkin_1111").values.should include(event.key)
subevents = subject.create("user_1_home", :fetch_subevents => true).items.first.subevents
subevents.last.data.should == event.data
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/service/protocol_spec.rb | spec/chronologic/service/protocol_spec.rb | require 'spec_helper'
describe Chronologic::Service::Protocol do
let(:protocol) { Chronologic::Service::Protocol }
it "records an entity" do
akk = {"name" => "akk"}
jp = {"name" => "Juan Pelota's"}
protocol.record("user_1", akk)
protocol.record("spot_1", jp)
hsh = {"user_1" => akk, "spot_1" => jp}
protocol.schema.object_for(["user_1", "spot_1"]).should == hsh
end
it "unrecords an entity" do
protocol.record("user_1", {"name" => "akk"})
protocol.unrecord("user_1")
protocol.schema.object_for("user_1").should == Hash.new
end
it "subscribes a subscriber key to a timeline key and populates a timeline" do
event = simple_event
protocol.publish(event)
protocol.subscribe("user_1_home", "user_1")
protocol.schema.subscribers_for("user_1").should == ["user_1_home"]
protocol.schema.timeline_events_for("user_1_home").values.should include(event.key)
end
it "subscribes a subscriber key to a timeline key with no backfill" do
event = simple_event
protocol.publish(event)
protocol.subscribe("user_1_home", "user_2", 'user_1', false)
protocol.schema.subscribers_for("user_2").should == ["user_1_home"]
protocol.schema.timeline_events_for("user_1_home").length.should == 0
end
it "unsubscribes a subscriber key from a timeline key" do
event = simple_event
protocol.publish(event)
protocol.subscribe("user_1_home", "user_1")
protocol.unsubscribe("user_1_home", "user_1")
protocol.schema.subscribers_for("user_1").should == []
protocol.schema.timeline_events_for("user_1_home").values.should == []
end
it 'checks whether a feed and a user are connected' do
protocol.subscribe('user_1_home', 'user_2', 'user_1')
protocol.subscribe('user_3_home', 'user_2') # No backlink, no connection
protocol.connected?('user_2', 'user_1').should == true
protocol.connected?('user_2', 'user_3').should == false
end
context "#publish" do
it "publishes an event to one or more timeline keys" do
event = Chronologic::Service::Event.new
event.key = "checkin_1111"
event.data = {"type" => "checkin", "message" => "I'm here!"}
event.objects = {"user" => "user_1", "spot" => "spot_1"}
event.timelines = ["user_1", "spot_1"]
protocol.subscribe("user_1_home", "user_1")
protocol.publish(event)
fetched = Chronologic::Service::Event.from_columns(protocol.schema.event_for(event.key))
fetched.data.should == event.data
fetched.objects.should == event.objects
protocol.schema.timeline_events_for("user_1_home").values.should include(event.key)
event.timelines.each do |t|
protocol.schema.timeline_events_for(t).values.should include(event.key)
end
end
it "publishes an event without fanout" do
event = simple_event
protocol.subscribe("user_1_home", "user_1")
uuid = protocol.publish(event, false)
protocol.schema.timeline_events_for("user_1_home").should_not include(event.key)
end
it "publishes an event twice raises an exception" do
event = simple_event
protocol.publish(event, false)
expect { protocol.publish(event, false) }.to raise_exception(Chronologic::Duplicate)
end
it "publishes an event with a forced timestamp" do
event = simple_event
t = Time.now.tv_sec - 180
protocol.publish(event, false, t)
protocol.schema.timeline_events_for(event.timelines.first).should include("#{t}_#{event.key}")
end
end
context "#unpublish" do
it "unpublishes an event from one or more timeline keys" do
event = simple_event
protocol.subscribe("user_1_home", "user_1")
protocol.publish(event)
protocol.unpublish(event)
protocol.schema.event_for(event.key).should == Hash.new
protocol.schema.timeline_events_for("user_1_home").should_not include(event.key)
event.timelines.each do |t|
protocol.schema.timeline_events_for(t).should_not include(event.key)
end
end
end
describe ".feed" do
it "uses the default feed strategy" do
Chronologic::Service::Feed.should_receive(:create)
protocol.feed('home')
end
it "uses the specified feed strategy" do
Chronologic::Service::ObjectlessFeed.should_receive(:create)
protocol.feed('home', :strategy => 'objectless')
end
it "raises if an unknown feed strategy is specified" do
expect { protocol.feed('home', :strategy => 'none') }.to raise_exception
end
end
describe ".fetch_event" do
it "fetches one event" do
event = simple_event
protocol.publish(event, false)
protocol.fetch_event(event.key).key.should eq(event.key)
end
it "raises Chronologic::NotFound if an event isn't present" do
expect { protocol.fetch_event('abc_123') }.to raise_exception(Chronologic::NotFound)
end
it "fetches an event with subevents" do
event = simple_event
protocol.publish(event, false)
nested = nested_event
protocol.publish(nested, false)
protocol.fetch_event(event.key).subevents.first.key.should eq(nested.key)
end
context "default fetch strategy (with objects)" do
it "fetches an event with objects" do
user = {'username' => 'ak'}
spot = {'name' => 'JP'}
protocol.record('user_1', user)
protocol.record('spot_1', spot)
event = simple_event
protocol.publish(simple_event, false)
protocol.fetch_event(event.key).objects['user'].should eq(user)
protocol.fetch_event(event.key).objects['spot'].should eq(spot)
end
it "fetches an event with subevents with objects" do
user = {'username' => 'ak'}
user2 = {'username' => 'ka'}
spot = {'name' => 'JP'}
protocol.record('user_1', user)
protocol.record('user_2', user2)
protocol.record('spot_1', spot)
event = simple_event
protocol.publish(event, false)
nested = nested_event
protocol.publish(nested, false)
event = protocol.fetch_event(event.key)
event.objects['user'].should eq(user)
event.objects['spot'].should eq(spot)
event.subevents.first.objects['user'].should eq(user2)
end
end
context "objectless fetch strategy" do
it "fetches an event with only object references" do
user = {'username' => 'ak'}
spot = {'name' => 'JP'}
protocol.record('user_1', user)
protocol.record('spot_1', spot)
event = simple_event
protocol.publish(simple_event, false)
options = {:strategy => "objectless"}
fetched_event = protocol.fetch_event(event.key, options)
fetched_event.objects['user'].should eq('user_1')
fetched_event.objects['spot'].should eq('spot_1')
end
it "fetches an event with subevents with objects" do
user = {'username' => 'ak'}
user2 = {'username' => 'ka'}
spot = {'name' => 'JP'}
protocol.record('user_1', user)
protocol.record('user_2', user2)
protocol.record('spot_1', spot)
event = simple_event
protocol.publish(event, false)
nested = nested_event
protocol.publish(nested, false)
options = {:strategy => "objectless"}
fetched_event = protocol.fetch_event(event.key, options)
fetched_event.objects['user'].should eq('user_1')
fetched_event.objects['spot'].should eq('spot_1')
fetched_event.subevents.first.objects['user'].should eq('user_2')
end
end
end
describe ".update_event" do
it "updates an event's attributes" do
event = simple_event
protocol.publish(event, false)
event.data['hotness'] = "It's so new!"
protocol.update_event(event)
protocol.fetch_event(event.key).data['hotness'].should eq("It's so new!")
end
it "updates an event's attributes and writes to all timelines" do
event = simple_event
protocol.publish(event, false)
event.timelines << 'testify_1'
protocol.update_event(event, true)
protocol.fetch_event(event.key).timelines.should include('testify_1')
protocol.schema.timeline_events_for('testify_1').values.should include(event.key)
end
it "updates an event's timelines and fans out to all timelines" do
protocol.subscribe('activity_feed', 'testify_1')
event = simple_event
protocol.publish(event, false)
event.timelines << 'testify_1'
protocol.update_event(event, true)
protocol.schema.timeline_events_for('activity_feed').values.should include(event.key)
end
it "cleans up timelines removed from the updated event" do
pending("Come back to this once timeline index key generation is figured out")
protocol.subscribe('activity_feed', 'testify_1')
event = simple_event
event.timelines << 'testify_1'
protocol.publish(event, true)
protocol.schema.timeline_events_for('activity_feed').values.should include(event.key)
event.timelines.delete('testify_1')
protocol.update_event(event, true)
protocol.schema.timeline_events_for('activity_feed').values.should_not include(event.key)
end
end
it "counts item in a feed" do
pending("Cheating on counts for a while")
populate_timeline
protocol.feed_count("user_1_home").should == 10
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/service/feed_spec.rb | spec/chronologic/service/feed_spec.rb | require 'spec_helper'
describe Chronologic::Service::Feed do
let(:protocol) { Chronologic::Service::Protocol }
subject { Chronologic::Service::Feed }
it_behaves_like "a feed strategy"
it "generates a feed for a timeline key" do
akk = {"name" => "akk"}
jp = {"name" => "Juan Pelota's"}
protocol.record("user_1", akk)
protocol.record("spot_1", jp)
event = simple_event
protocol.subscribe("user_1_home", "user_1")
protocol.publish(event)
["user_1", "spot_1", "user_1_home"].each do |t|
feed = subject.create(t).items
feed[0].data.should == event.data
feed[0].objects["user"].should == protocol.schema.object_for("user_1")
feed[0].objects["spot"].should == protocol.schema.object_for("spot_1")
end
end
it "generates a feed for a timeline key, fetching nested timelines" do
akk = {"name" => "akk"}
sco = {"name" => "sco"}
jp = {"name" => "Juan Pelota's"}
protocol.record("user_1", akk)
protocol.record("user_2", sco)
protocol.record("spot_1", jp)
event = Chronologic::Service::Event.new
event.key = "checkin_1111"
event.data = {"type" => "checkin", "message" => "I'm here!"}
event.objects = {"user" => "user_1", "spot" => "spot_1"}
event.timelines = ["user_1", "spot_1"]
protocol.subscribe("user_1_home", "user_1")
event = protocol.publish(event)
event = Chronologic::Service::Event.new
event.key = "comment_1111"
event.data = {"type" => "comment", "message" => "Me too!", "parent" => "checkin_1111"}
event.objects = {"user" => "user_2"}
event.timelines = ["checkin_1111"]
protocol.publish(event)
event = Chronologic::Service::Event.new
event.key = "comment_2222"
event.data = {"type" => "comment", "message" => "Great!", "parent" => "checkin_1111"}
event.objects = {"user" => "user_1"}
event.timelines = ["checkin_1111"]
protocol.publish(event)
protocol.schema.timeline_events_for("checkin_1111").values.should include(event.key)
subevents = subject.create("user_1_home", :fetch_subevents => true).items.first.subevents
subevents.last.data.should == event.data
subevents.first.objects["user"].should == protocol.schema.object_for("user_2")
subevents.last.objects["user"].should == protocol.schema.object_for("user_1")
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/service/event_spec.rb | spec/chronologic/service/event_spec.rb | require 'spec_helper'
describe Chronologic::Service::Event do
it_behaves_like "a CL event"
subject do
described_class.from_attributes(
:key => "event_1",
:data => {"foo" => {"one" => "two"}},
:objects => {"user" => "user_1", "spot" => "spot_1"},
:timelines => ["user_1", "sxsw"],
:token => [Time.now.tv_sec, "event_1"].join(':')
)
end
it "serializes structured data columns" do
subject.to_columns["data"].should == MultiJson.encode(subject.data)
subject.to_columns["objects"].should == MultiJson.encode(subject.objects)
subject.to_columns["timelines"].should == MultiJson.encode(subject.timelines)
end
it "loads an event fetched from Cassandra" do
new_event = described_class.from_columns(subject.to_columns)
new_event.token.should == subject.token
new_event.data.should == subject.data
new_event.objects.should == subject.objects
new_event.timelines.should == subject.timelines
end
it "loads an empty event" do
empty_event = described_class.from_columns({})
empty_event.token.should == ''
empty_event.data.should == Hash.new
empty_event.objects.should == Hash.new
empty_event.timelines.should == Array.new
end
it "encodes for sending back to HTTP clients" do
subject.to_client_encoding["data"].should == subject.data
subject.to_client_encoding["objects"].should == subject.objects
subject.to_client_encoding["timelines"].should == subject.timelines
subject.to_client_encoding["subevents"].should == subject.subevents
subject.to_client_encoding["key"].should == subject.key
end
it "populates token" do
subject.key = "thingoid_1"
subject.set_token
subject.token.should match(/thingoid_1/)
end
it "populates token with a forced timestamp" do
subject.key = "thingoid_1"
subject.set_token(123)
subject.token.should eq("123_thingoid_1")
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/service/app_spec.rb | spec/chronologic/service/app_spec.rb | require 'spec_helper'
require 'rack/test'
describe Chronologic::Service::App do
include Rack::Test::Methods
let(:protocol) { Chronologic::Service::Protocol }
it "writes a new entity record" do
data = {
"name" => "Juan Pelota's",
"awesome_factor" => "100"
}
post "/object", {:object_key => "spot_1", :data => data}
last_response.status.should == 201
Chronologic.schema.object_for("spot_1").should == data
end
it "reads an entity record" do
data = {
"name" => "Juan Pelota's",
"awesome_factor" => "100"
}
protocol.record("spot_1", data)
get "/object/spot_1"
last_response.status.should == 200
json_body.should == data
end
it "deletes an entity record" do
data = {
"name" => "Juan Pelota's",
"awesome_factor" => "100"
}
protocol.record("spot_1", data)
delete "/object/spot_1"
last_response.status.should == 204
Chronologic.schema.object_for("spot_1").should == Hash.new
end
it "subscribes a subscriber to a timeline" do
subscription = {
"timeline_key" => "user_1_home",
"subscriber_key" => "user_2",
"backlink_key" => "user_1"
}
post "/subscription", subscription
last_response.status.should == 201
Chronologic.schema.subscribers_for("user_2").should include("user_1_home")
Chronologic.schema.followers_for("user_2").should include("user_1")
end
it "subscribes a subscriber to a timeline without backfill" do
Chronologic.schema.create_timeline_event('user_2', 'abc123', 'event_1')
subscription = {
"timeline_key" => "user_1_home",
"subscriber_key" => "user_2",
"backlink_key" => "user_1",
"backfill" => "false"
}
post "/subscription", subscription
last_response.status.should == 201
Chronologic.schema.subscribers_for("user_2").should include("user_1_home")
Chronologic.schema.followers_for("user_2").should include("user_1")
Chronologic.schema.timeline_for("user_1_home").length.should == 0
end
it "unsubscribes a subscriber to a timeline" do
protocol.subscribe("user_2", "user_1_home")
delete "/subscription/user_2/user_1_home"
last_response.status.should == 204
Chronologic.schema.subscribers_for("user_2").should_not include("user_1_home")
end
it 'checks social connection for a timeline backlink and a subscriber key' do
# Set up connections
protocol.subscribe('user_bo_feed', 'user_ak', 'user_bo') # w/ backlink
protocol.subscribe('user_ak_feed', 'user_bo', 'user_ak')
protocol.subscribe('user_bs_feed', 'user_bo', 'user_bs') # No recip.
get '/subscription/is_connected', {
'timeline_backlink' => 'user_ak',
'subscriber_key' => 'user_bo'
}
last_response.status.should == 200
obj = MultiJson.decode(last_response.body)
obj['user_bo'].should == true
end
context "POST /event" do
it "publishes an event" do
event = {
"key" => "checkin_1212",
"data" => MultiJson.encode({"type" => "checkin", "message" => "I'm here!"}),
"objects" => MultiJson.encode({"user" => "user_1", "spot" => "spot_1"}),
"timelines" => MultiJson.encode(["user_1", "spot_1"])
}
post "/event", event
last_response.status.should == 201
result = Chronologic.schema.event_for("checkin_1212")
result["data"].should == event["data"]
result["objects"].should == event["objects"]
last_response.headers["Location"].should match(%r!/event/#{event["key"]}!)
end
it "returns an error if a duplicate event is published" do
event = {
"key" => "checkin_1212",
"data" => MultiJson.encode({"type" => "checkin", "message" => "I'm here!"}),
"objects" => MultiJson.encode({"user" => "user_1", "spot" => "spot_1"}),
"timelines" => MultiJson.encode(["user_1", "spot_1"])
}
post "/event?fanout=0", event
post "/event?fanout=0", event
last_response.status.should == 409
last_response.body.should match(/duplicate event/)
end
it "publishes an event without fanout" do
event = {
"key" => "checkin_1212",
"data" => MultiJson.encode({"type" => "checkin", "message" => "I'm here!"}),
"objects" => MultiJson.encode({"user" => "user_1", "spot" => "spot_1"}),
"timelines" => MultiJson.encode(["user_1", "spot_1"])
}
protocol.subscribe("user_1_home", "user_1")
post "/event?fanout=0", event
last_response.status.should == 201
result = Chronologic.schema.event_for("checkin_1212")
result["data"].should == event["data"]
result["objects"].should == event["objects"]
Chronologic.schema.timeline_events_for("user_1_home").values.should_not include(event["key"])
end
it "publishes an event with a forced timestamp" do
event = {
"key" => "checkin_1212",
"data" => MultiJson.encode({"type" => "checkin", "message" => "I'm here!"}),
"objects" => MultiJson.encode({"user" => "user_1", "spot" => "spot_1"}),
"timelines" => MultiJson.encode(["user_1", "spot_1"])
}
t = Time.now.tv_sec - 120
post "/event?fanout=0&force_timestamp=#{t}", event
last_response.status.should == 201
Chronologic.schema.timeline_events_for('user_1').keys.should include("#{t}_checkin_1212")
end
end
it "unpublishes an event" do
uuid = protocol.publish(an_event)
delete "/event/checkin_1111"
last_response.status.should == 204
Chronologic.schema.event_for("checkin_1111").should == Hash.new
end
it "updates an event" do
protocol.publish(simple_event)
event = simple_event(:client)
put "/event/#{event.key}", event.to_transport
last_response.status.should eq(204)
last_response.headers["Location"].should match(%r!/event/#{event.key}!)
end
it "updates an event and its timelines" do
event = simple_event(:client)
protocol.publish(simple_event)
event.timelines << 'foo_1'
put "/event/#{event.key}?update_timelines=true", event.to_transport
last_response.status.should eq(204)
Chronologic.schema.timeline_events_for('foo_1').values.should include(event.key)
last_response.headers["Location"].should match(%r!/event/#{event.key}!)
end
it 'fetches a single event' do
event = simple_event
uuid = protocol.publish(event)
get "/event/#{event.key}"
last_response.status.should == 200
json_body.should include('event')
json_body['event'].should_not include('timestamp')
json_body['event'].should include('key', 'data', 'timelines', 'objects')
end
it "returns 404 if an event isn't found" do
get "/event/thingy_123"
last_response.status.should == 404
end
it "reads a timeline feed with a non-default strategy" do
Chronologic::Service::ObjectlessFeed.should_receive(:create).and_return(double.as_null_object)
get "/timeline/user_1_home?strategy=objectless"
end
it "reads a timeline feed" do
jp = {"name" => "Juan Pelota's", "awesome_factor" => "100"}
keeg = {"name" => "Keegan", "awesome_factor" => "109"}
protocol.record("spot_1", jp)
protocol.record("user_1", keeg)
protocol.subscribe("user_1_home", "user_1")
event = simple_event
uuid = protocol.publish(event)
get "/timeline/user_1_home"
last_response.status.should == 200
obj = json_body
obj["feed"].length.should == 1
result = obj["feed"].first
result["data"].should == event.data
result["objects"]["user"].should == keeg
result["objects"]["spot"].should == jp
end
it "reads a timeline feed with page and per_page parameters" do
populate_timeline
get "/timeline/user_1_home", :per_page => 5
json_body.should have_key("next_page")
# We're cheating on counts for a while
# json_body["count"].should eq(10)
json_body["feed"].length.should == 5
end
it "reads a timeline with subevents" do
akk = {"name" => "akk"}
sco = {"name" => "sco"}
jp = {"name" => "Juan Pelota's"}
protocol.record("user_1", akk)
protocol.record("user_2", sco)
protocol.record("spot_1", jp)
event = Chronologic::Service::Event.from_attributes(
"key" => "checkin_1111",
"data" => {"type" => "checkin", "message" => "I'm here!"},
"objects" => {"user" => "user_1", "spot" => "spot_1"},
"timelines" => ["user_1", "spot_1"]
)
protocol.subscribe("user_1_home", "user_1")
event = protocol.publish(event)
event = Chronologic::Service::Event.from_attributes(
"key" => "comment_1111",
"data" => {"type" => "comment", "message" => "Me too!", "parent" => "checkin_1111"},
"objects" => {"user" => "user_2"},
"timelines" => ["checkin_1111"]
)
protocol.publish(event)
event = Chronologic::Service::Event.from_attributes(
"key" => "comment_2222",
"data" => {"type" => "comment", "message" => "Great!", "parent" => "checkin_1111"},
"objects" => {"user" => "user_1"},
"timelines" => ["checkin_1111"]
)
protocol.publish(event)
get "/timeline/user_1_home", :subevents => true
obj = json_body
result = obj["feed"].first
result["subevents"].length.should == 2
end
def an_event
Chronologic::Service::Event.from_attributes(
"key" => "checkin_1111",
"data" => {"type" => "checkin", "message" => "I'm here!"},
"objects" => {"user" => "user_1", "spot" => "spot_1"},
"timelines" => ["user_1", "spot_1"]
)
end
def json_body
MultiJson.decode(last_response.body)
end
def app
logger = Logger.new(STDOUT)
logger.level = Logger::WARN
Chronologic::Service::App.logger = logger
Chronologic::Service::App.new
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/client/connection_spec.rb | spec/chronologic/client/connection_spec.rb | require 'spec_helper'
describe Chronologic::Client::Connection do
let(:client) { Chronologic::Client::Connection.new('http://localhost:3000') }
it "records an object" do
stub_request(:post, "http://localhost:3000/object").
to_return(:status => 201)
client.record("user_1", {"name" => "akk"}).should be_true
WebMock.should have_requested(:post, "http://localhost:3000/object").
with(:body => {"object_key" => "user_1", "data" => {"name" => "akk"}})
end
it "unrecords an object" do
stub_request(:delete, "http://localhost:3000/object/spot_1").
to_return(:status => 204)
client.unrecord("spot_1").should be_true
WebMock.should have_requested(:delete, "http://localhost:3000/object/spot_1")
end
it "retrieves an object" do
object = {
'test' => 'abc'
}
stub_request(
:get,
"http://localhost:3000/object/spot_1"
).to_return(
:status => 200,
:body => object.to_json,
:headers => {'Content-Type' => 'application/json'}
)
result = client.retrieve("spot_1")
WebMock.should have_requested(
:get,
"http://localhost:3000/object/spot_1"
)
result.should eq(object)
end
it "subscribes a user to a timeline" do
stub_request(:post, "http://localhost:3000/subscription").
to_return(:status => 201)
client.subscribe("user_2", "user_1_home", "user_1").should be_true
WebMock.should have_requested(:post, "http://localhost:3000/subscription").
with(
:body => {
"subscriber_key" => "user_1_home",
"timeline_key" => "user_2",
"backlink_key" => "user_1",
"backfill" => "true"
}
)
end
it 'subscribes a user to a timline without performing backfill' do
stub_request(:post, "http://localhost:3000/subscription").
to_return(:status => 201)
client.subscribe("user_2", "user_1_home", "user_1", false).should be_true
WebMock.should have_requested(:post, "http://localhost:3000/subscription").
with(
:body => {
"subscriber_key" => "user_1_home",
"timeline_key" => "user_2",
"backlink_key" => "user_1",
"backfill" => "false"
}
)
end
it "unsubscribes a user to a timeline" do
stub_request(
:delete,
"http://localhost:3000/subscription/user_1_home/user_2"
).to_return(:status => 204)
client.unsubscribe("user_1_home", "user_2").should be_true
WebMock.should have_requested(:delete, "http://localhost:3000/subscription/user_1_home/user_2")
end
it "checks whether a feed is connected to another feed" do
query = {
'subscriber_key' => 'user_ak',
'timeline_backlink' => 'user_bf'
}.map { |pair| pair.join('=') }.join('&')
resp = {
'subscriber_key' => true
}
stub_request(:get, "http://localhost:3000/subscription/is_connected?#{query}").
to_return(
:status => 200,
:body => resp
)
client.connected?('user_ak', 'user_bf').should be_true
WebMock.should have_requested(:get, "http://localhost:3000/subscription/is_connected?#{query}")
end
it "publishes an event" do
event = simple_event(:client)
t = Time.now.utc.tv_sec
body = event.to_transport
stub_request(:post, "http://localhost:3000/event?fanout=1&force_timestamp=#{t}").
with(:body => body).
to_return(
:status => 201,
:headers => {"Location" => "/event/checkin_1"}
)
client.publish(event, true, t).should match(/[\w\d-]*/)
event.should be_published
WebMock.should have_requested(:post, "http://localhost:3000/event?fanout=1&force_timestamp=#{t}").
with(:body => body)
end
it "unpublishes an event" do
event_key = "checkin_1"
stub_request(
:delete,
"http://localhost:3000/event/#{event_key}"
).to_return(:status => 204)
client.unpublish(event_key).should be_true
WebMock.should have_requested(:delete, "http://localhost:3000/event/#{event_key}")
end
it 'updates an event' do
event = simple_event(:client)
url = "http://localhost:3000/event/#{event.key}?update_timelines=false"
body = event.to_transport
stub_request(:put, url).
with(:body => body).
to_return(
:status => 201,
:headers => {"Location" => "/event/checkin_1/abc123"}
)
client.update(event, false).should eq("/event/checkin_1/abc123")
WebMock.should have_requested(:put, url).
with(:body => body)
end
it 'updates an event with timeline changes' do
event = simple_event(:client)
url = "http://localhost:3000/event/#{event.key}?update_timelines=true"
body = event.to_transport
stub_request(:put, url).
with(:body => body).
to_return(
:status => 201,
:headers => {"Location" => "/event/checkin_1/abc123"}
)
client.update(event, true).should eq("/event/checkin_1/abc123")
WebMock.should have_requested(:put, url).
with(:body => body)
end
it "fetches an event" do
event = simple_event(:client)
stub_request(
:get,
"http://localhost:3000/events/#{event.key}"
).to_return(
:status => 200,
:body => {'event' => simple_event.to_client_encoding}.to_json,
:headers => {'Content-Type' => 'application/json'}
)
result = client.fetch("/events/#{event.key}")
WebMock.should have_requested(
:get,
"http://localhost:3000/events/#{event.key}"
)
result.should be_a(Chronologic::Client::Event)
end
it "fetches a timeline" do
event = simple_event
stub_request(:get, "http://localhost:3000/timeline/user_1_home?subevents=false&page=abc-123&per_page=5").
to_return(
:status => 200,
:body => {"feed" => [event.to_client_encoding]}.to_json,
:headers => {"Content-Type" => "application/json"}
)
result = client.timeline("user_1_home", :subevents => false, :page => "abc-123", :per_page => "5")
WebMock.should have_requested(:get, "http://localhost:3000/timeline/user_1_home?subevents=false&page=abc-123&per_page=5")
result["feed"].length.should == 1
(result["feed"].first.keys - ["timestamp"]).each do |k|
result["feed"].first[k].should == event.send(k)
end
end
it "fetches a timeline with subevents" do
event = simple_event
event.subevents = [nested_event]
stub_request(:get, "http://localhost:3000/timeline/user_1_home?subevents=true").
to_return(
:status => 200,
:body => {"feed" => [event.to_client_encoding]}.to_json,
:headers => {"Content-Type" => "application/json"}
)
result = client.timeline("user_1_home", :subevents => true)
WebMock.should have_requested(:get, "http://localhost:3000/timeline/user_1_home?subevents=true")
result["items"].first.subevents.length.should == 1
end
it "provides an instance of itself" do
Chronologic::Client::Connection.instance = client
Chronologic::Client::Connection.instance.should == client
end
context "#handle" do
it "parses JSON errors" do
resp = double(
:response,
:code => 500,
:content_type => 'application/json',
:body => MultiJson.encode({})
)
expect { client.handle(resp, 'message') }.to raise_exception(Chronologic::ServiceError)
end
it "parses duplicate errors" do
resp = double(:response, :code => 409, :body => 'duplicate!')
expect { client.handle(resp, 'message') }.to raise_exception(Chronologic::Duplicate)
end
it "parses not found errors" do
resp = double(:response, :code => 404)
expect { client.handle(resp, 'message') }.to raise_exception(Chronologic::NotFound)
end
it "parses generic errors" do
resp = double(:response, :code => 500, :content_type => 'text/plain')
expect { client.handle(resp, 'message') }.to raise_exception(Chronologic::Exception)
end
it "yields on success" do
called = false
resp = double(:response, :code => 201)
client.handle(resp, 'boom') { called = true }
called.should be_true
end
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/client/fake_spec.rb | spec/chronologic/client/fake_spec.rb | require 'spec_helper'
describe Chronologic::Client::Fake do
def valid_event_hash
{
'key' => 'event_1',
'timelines' => [],
'objects' => {},
'subevents' => [],
'data' => {}
}
end
def valid_event
Chronologic::Client::Event.from_attributes(valid_event_hash)
end
describe "#record" do
it "stores an object" do
subject.record("thing_1", {"thingy" => "thingoid"})
subject.objects.should include("thing_1" => {"thingy" => "thingoid"})
end
it "raises an exception if data is not a hash" do
expect { subject.record("thing_1", Array.new) }.to raise_exception(ArgumentError)
end
end
describe "#unrecord" do
it "removes a stored object" do
subject.record("thing_1", {"thingy" => "thingoid"})
subject.unrecord("thing_1")
subject.objects.should be_empty
end
end
describe "#subscribe" do
it "creates a subscription" do
subject.subscribe("user_akk", "user_mt_feed", "user_mt")
subject.subscribers.should include("user_akk" => {"user_mt_feed" => "user_mt"})
end
it "backfills the specified timeline"
end
describe "#unsubscribe" do
it "removes a subscription" do
subject.subscribe("user_akk", "user_mt_feed", "user_mt")
subject.unsubscribe("user_akk", "user_mt_feed")
subject.subscribers["user_akk"].should be_empty
end
it "removes unsubscribed entries from the timeline"
end
describe "#connected?" do
it "checks if a subscriber is connected with a backlink to a consumer" do
subject.subscribe("user_akk", "user_mt_feed", "user_mt")
subject.should be_connected("user_akk", "user_mt")
end
end
describe "#publish" do
it "creates a new event" do
event = valid_event
subject.publish(event)
subject.events.keys.should include(event.key)
end
it "writes the event to each specified timeline" do
event = valid_event
event.timelines = ['foo']
subject.publish(event)
subject.timelines['foo'].values.should include('event_1')
end
it "writes the event to subscribed timelines" do
subject.subscribe('user_1', 'user_2_feed')
event = valid_event
event.timelines = ['user_1']
subject.publish(event)
subject.timelines['user_2_feed'].values.should include(event.key)
end
it "returns a CL key instead of a URL" do
event = valid_event
subject.publish(event).should eq(event.key)
end
it "raises an exception if event is not a Chronologic::Event" do
expect { subject.publish("string") }.to raise_exception(ArgumentError)
end
end
describe "#fetch" do
it "returns nil if an event isn't found" do
subject.fetch('gobbeldygook').should be_nil
end
it "retrieves an event" do
event = valid_event
subject.publish(event)
subject.fetch(event.key).should eq(event)
end
it "copies retrieved events" do
event = valid_event
subject.publish(event)
subject.fetch(event.key).should_not equal(event)
end
it "populates objects on fetched events" do
object = {"thingy" => '1234'}
subject.record('object_1', object)
event = valid_event.tap do |e|
e.key = 'event_1'
e.objects = {'gizmos' => ['object_1']}
end
subject.publish(event)
subject.fetch(event.key).objects['gizmos']['object_1'].should eq(object)
end
it "not return a Chronologic::Event" do
event = valid_event
subject.publish(event)
subject.fetch(event.key).class.should_not be_kind_of(Chronologic::Event)
end
it "fetches subevents on fetched events" do
event = valid_event
subject.publish(event)
subevent = valid_event.tap do |e|
e.key = 'subevent_1'
e.timelines = [event.key]
end
subject.publish(subevent)
subject.fetch(event.key).subevents.should include(subevent)
end
it "populates objects on fetched subevents" do
event = valid_event
subject.publish(event)
subevent = valid_event.tap do |e|
e.key = 'subevent_1',
e.timelines = [event.key],
e.objects = {'gizmos' => ['object_1']}
end
subject.publish(subevent)
object = {"thingy" => "weird"}
subject.record('object_1', object)
fetched = subject.fetch(event.key).subevents.first
fetched.objects['gizmos'].should include('object_1' => object)
end
end
describe "#update" do
it "rewrites an existing event" do
event = valid_event
subject.publish(event)
updated = event.dup
updated.data = {"happy" => "yep!"}
subject.update(updated)
subject.fetch(event.key).should eq(updated)
end
end
describe "#timeline" do
let(:events) do
10.times.map do |i|
event = valid_event.tap do |e|
e.key = "event_#{i}",
e.timelines = ['home']
end
end
end
before(:each) { events.each { |e| subject.publish(e) } }
it "fetches a page of events on a timeline" do
pending("Get this working with token-based timelines")
feed = subject.timeline('home')
feed['count'].should eq(10)
feed['items'].should eq(events)
end
it "fetches the specified number of events" do
pending("Get this working with token-based timelines")
feed = subject.timeline('home', 'per_page' => 5)
feed['count'].should eq(10)
feed['items'].length.should eq(5)
end
it "fetches from a page offset" do
pending("Get this working with token-based timelines")
token = subject.timeline('home', 'per_page' => 5)['next_page']
feed = subject.timeline('home', 'per_page' => 5, 'page' => token)
feed['count'].should eq(10)
feed['items'].length.should eq(5)
feed['items'].should eq(events.last(5))
end
it "fetches objects on events" do
object = {"doneness" => "so close"}
subject.record('object_1', object)
event = valid_event.tap do |e|
e.key = 'event_100',
e.timelines = ['with_object'],
e.objects = {"object" => ['object_1']}
end
subject.publish(event)
feed = subject.timeline('with_object')
feed['items'].first.objects["object"].should eq({"object_1" => object})
end
it "fetches subevents on events" do
parent = valid_event.tap do |e|
e.key = 'event_1'
e.timelines = ['with_subevent']
end
subevent = valid_event.tap do |e|
e.key = 'event_2'
e.timelines = ['event_1']
end
subject.publish(parent)
subject.publish(subevent)
feed = subject.timeline('with_subevent')
feed['items'].first.subevents.should eq([subevent])
end
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/chronologic/client/event_spec.rb | spec/chronologic/client/event_spec.rb | require 'spec_helper'
describe Chronologic::Client::Event do
it_behaves_like "a CL event"
let(:event) { simple_event(:client) }
it "serializes for HTTP transport" do
event.to_transport.should_not have_key("timestamp")
event.to_transport["data"].should == MultiJson.encode(event.data)
event.to_transport["objects"].should == MultiJson.encode(event.objects)
event.to_transport["timelines"].should == MultiJson.encode(event.timelines)
event.to_transport["key"].should == event.key
end
it "is unpublished by default" do
event.published?.should == false
end
it "toggles published state" do
event.published!
event.published?.should == true
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/functional/api_spec.rb | spec/functional/api_spec.rb | require 'functional_helper'
describe "The Chronologic API" do
let(:schema) { Chronologic::Service::Schema }
before do
Chronologic.connection = Cassandra.new('ChronologicTest')
end
context "POST /subscription" do
it "creates a subscription from timeline key to subscriber key" do
# home <- tech
connection.subscribe("home", "tech")
schema.subscribers_for("tech").should include("home")
end
it "creates a subscription from timeline to subscriber with a backlink" do
# home <- tech
connection.subscribe("home", "tech", "home")
schema.followers_for("tech").should include("home")
end
it "backfills existing timeline events to the subscriber" do
5.times do |n|
event = simple_event(:client)
event.key = "event_#{n}"
event.timelines = ["tech"]
connection.publish(event)
end
# home <- tech
connection.subscribe("home", "tech", nil, true)
connection.timeline("home")["items"].should have(5).items
end
end
context "DELETE /subscription/[subscriber_key]/[timeline_key]" do
it "removes the subscription from timeline key to subscriber key" do
# events flow "tech" -> "home"
connection.subscribe("home", "tech")
schema.subscribers_for("tech").should include("home")
# events flow "tech" -> "home"
connection.unsubscribe("home", "tech")
schema.subscribers_for("tech").should_not include("home")
end
it "removes events from subscriber key on timeline key" do
# events flow "tech" -> "home"
connection.subscribe("home", "tech")
event = simple_event(:client)
event.timelines = ["tech"]
connection.publish(event)
connection.timeline("home")["items"].should have(1).item
# events flow "tech" -> "home"
connection.unsubscribe("home", "tech")
connection.timeline("home")["items"].should be_empty
end
end
context "GET /event/[event_key]" do
it "returns an event" do
event = simple_event(:client)
url = connection.publish(simple_event(:client))
connection.fetch(url).key.should eq(event.key)
end
it "returns 404 if the event isn't present" do
expect { connection.fetch('/event/thingy_123') }.to raise_exception(Chronologic::NotFound)
end
end
context "PUT /event/[event_key]" do
it "updates an existing event" do
event = simple_event(:client)
url = connection.publish(simple_event(:client))
event.data["brand-new"] = "totally fresh!"
connection.update(event)
connection.fetch(url).data["brand-new"].should eq("totally fresh!")
end
it "reprocesses timelines if update_timeline is set" do
event = simple_event(:client)
url = connection.publish(simple_event(:client))
event.timelines << 'another_timeline'
connection.update(event, true)
connection.timeline('another_timeline')["items"].first.key.should eq(event.key)
end
end
context "DELETE /event/[event_key]" do
let(:event) { simple_event(:client) }
it "removes the specified event" do
url = connection.publish(simple_event(:client))
connection.fetch(url).should be_true
connection.unpublish(event.key)
expect { connection.fetch(url).should }.to raise_exception(Chronologic::NotFound)
end
it "indicates success if the event isn't found" do
url = "abc123"
connection.unpublish(url).should be_true
end
it "removes the event from all timelines it was posted to" do
url = connection.publish(event)
event.timelines.each do |t|
connection.timeline(t)["items"].
map { |e| e.key }.
should include(event.key)
end
connection.unpublish(event.key)
event.timelines.each do |t|
connection.timeline(t)["items"].
map { |e| e.key }.
should_not include(event.key)
end
end
it "removes the event from all timelines subscribed to the timelines it was on" do
subscribed_timelines = event.timelines.map do |t|
10.times.map do |i|
other = "other_#{i}"
connection.subscribe(other, t)
other
end
end.flatten
connection.publish(event)
subscribed_timelines.each do |t|
connection.timeline(t)["items"].
map { |e| e.key }.
should include(event.key)
end
connection.unpublish(event.key)
subscribed_timelines.each do |t|
connection.timeline(t)["items"].
map { |e| e.key }.
should_not include(event.key)
end
end
end
context "GET /timeline/[timeline_key]" do
it "does not return a next page key if there is no more data" do
events = make_timeline # 10 events
feed = connection.timeline("user_1_feed", :per_page => events.length)
feed["next_page"].should be_nil
end
it "returns 404 if the timeline key isn't found"
it "uses next_page to page through a timeline" do
events = make_timeline # 10 events
feed = connection.timeline("user_1_feed", :per_page => 5)
feed = connection.timeline("user_1_feed", :per_page => 5, :page => feed["next_page"])
feed["next_page"].should be_nil
end
end
def make_timeline
jp = {"name" => "Juan Pelota's"}
connection.record("spot_1", jp)
events = []
%w{sco jc am pb mt rm ak ad rs bf}.each_with_index do |u, i|
record = {"name" => u}
key = "user_#{i}"
connection.record(key, record)
connection.subscribe("user_1_feed", "user_#{i}")
event = simple_event(:client)
event.key = "checkin_#{i}"
event.objects["user"] = key
event.timelines = [key, "spot_1"]
events << event
connection.publish(event)
end
return events
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/functional/privacy_spec.rb | spec/functional/privacy_spec.rb | require 'functional_helper'
describe "Privacy controls in Chronologic" do
include Rack::Test::Methods
# Rewrite this from a chronologic client
it "checks whether a user can see events for another user" do
pending("Come back to this when you're good and sure about it")
post '/subscription', {
'timeline_key' => 'user_ak_feed',
'subscriber_key' => 'user_bo',
'timeline_backlink' => 'user_ak'
}
get '/subscription/is_connected', {
'subscriber_key' => 'user_bo',
'timeline_backlink' => 'user_ak'
}
last_response.status.must_equal 200
obj = MultiJson.decode(last_response.body)
obj['user_bo'].must_equal true
end
it "removes private events from a timeline if the users are not connected"
it "includes private events in a timeline if the users are connected"
def app
logger = Logger.new(STDOUT)
logger.level = Logger::WARN
Chronologic::Service.logger = logger
Chronologic::Service.new
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/spec/functional/use_cases_spec.rb | spec/functional/use_cases_spec.rb | require 'functional_helper'
describe "Chronologic API uses cases" do
it "publish an event with subevents, remove the event and subevents, get a blank timeline" do
event = simple_event(:client)
comment0 = Chronologic::Client::Event.from_attributes(
'key' => 'comment_1',
'data' => {'type' => 'comment', 'message' => 'Me too!', 'parent' => 'checkin_1'},
'objects' => {'user' => 'user_2'},
'timelines' => ['checkin_1']
)
event.timelines << 'user_2' # Add a timeline to the parent event
connection.publish(comment0)
connection.publish(event)
comment1 = Chronologic::Client::Event.from_attributes(
'key' => 'comment_2',
'data' => {'type' => 'comment', 'message' => 'Me three!', 'parent' => 'checkin_1'},
'objects' => {'user' => 'user_3'},
'timelines' => ['checkin_1']
)
connection.publish(comment1)
event.timelines << 'user_3'
connection.update(event)
connection.unpublish('comment_2')
event.timelines.delete('user_3')
connection.update(event)
connection.unpublish('comment_1')
event.timelines.delete('user_2')
connection.update(event)
connection.unpublish(event.key)
connection.timeline(event.timelines.first)["feed"].should be_empty
end
it "publish an event with a forced timestamp so it appears in the right position" do
old_event = simple_event(:client).tap do |e|
e.key = 'event_2'
e.data = {'message' => 'This appears last'}
end
new_event = simple_event(:client).tap do |e|
e.key = 'event_1'
e.data = {'message' => 'This appears first'}
end
connection.publish(new_event)
connection.publish(old_event, true, Time.now.tv_sec - 60)
feed = connection.timeline(old_event.timelines.first)
feed["items"].first.key.should eq(new_event.key)
feed["items"].last.key.should eq(old_event.key)
end
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/examples/paginate.rb | examples/paginate.rb | require "pp"
require "chronologic"
Chronologic.connection = Cassandra.new("ChronologicTest")
puts "Paginating with Chronologic::Schema"
page = Chronologic::Schema.timeline_for("user_1165", :per_page => 5).keys
puts "First/last: #{page.first}/#{page.last}"
pp Chronologic::Schema.timeline_for("user_1165", :per_page => 5, :page => page.last)
puts
puts "Paginating with Chronologic::Feed"
feed = Chronologic::Feed.new("user_1165", 5)
feed.fetch
puts "First/last: #{feed.previous_page}/#{feed.next_page}"
# pp Chronologic::Feed.fetch("user_1165", :per_page => 5, :page => feed.next_key)
puts
puts "Paginating with Chronologic::Feed and will_paginate"
feed = Chronologic::Feed.new("user_1165", 5)
feed.fetch
puts "First/last: #{feed.previous_page}/#{feed.next_page}"
next_feed = Chronologic::Feed.new("user_1165", 5, feed.next_page)
next_feed.fetch
puts "First/last: #{next_feed.previous_page}/#{next_feed.next_page}"
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/examples/05_gowalla.rb | examples/05_gowalla.rb | # Create some objects, create some subscriptions, publish some events, fetch
require 'boilerplate'
connection = Chronologic::Client::Connection.new('http://localhost:7979')
connection.record("user:ak", {"long_name" => "Adam Keys"})
connection.record("user:rs", {"long_name" => "Richard Schneeman"})
connection.record("user:mt", {"long_name" => "Mattt Thompson"})
connection.record("user:am", {"long_name" => "Adam Michaela"})
connection.record("spot:lsrc", {"name" => "Lone Star Ruby Conference"})
connection.subscribe("passport:ak", "friends:rs")
connection.subscribe("passport:ak", "friends:am")
connection.subscribe("passport:ak", "friends:mt")
event = Chronologic::Event.new
event.key = "checkin:1"
event.timestamp = Time.now
event.data = {"message" => "I'm giving a talk!"}
event.objects = {"user" => ["user:ak"], "spots" => ["spot:lsrc"]}
event.timelines = ["passport:ak"]
connection.publish(event)
subevent = Chronologic::Event.new
subevent.key = "comment:1"
subevent.timestamp = Time.now
subevent.data = {"message" => "Me too!"}
subevent.parent = "checkin:1"
subevent.objects = {"user" => ["user:rs"]}
subevent.timelines = ["checkin:1"]
connection.publish(subevent)
feed = connection.timeline("friends:rs")
pp feed['items'].first
feed = connection.timeline("friends:am")
pp feed['items'].first
feed = connection.timeline("friends:mt")
pp feed['items'].first
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/examples/boilerplate.rb | examples/boilerplate.rb | require 'rubygems'
require 'bundler/setup'
require 'pp'
require 'chronologic'
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/examples/gowalla.rb | examples/gowalla.rb | #!/usr/bin/env ruby
$:.unshift File.expand_path(File.dirname(__FILE__) + '/../lib')
require 'chronologic'
c = Chronologic::Client.new
c.clear!
puts "Create objects for users, spots, trips, highlights"
c.object(:user_1, {:name => 'Scott Raymond'})
c.object(:user_2, {:name => 'Josh Williams'})
c.object(:spot_1, {:name => 'Gowalla HQ'})
c.object(:spot_2, {:name => 'Juan Pelota'})
c.object(:trip_1, {:name => 'Visit 3 Coffeeshops!'})
c.object(:highlight_type_1, {:name => 'My Happy Place'})
puts "Update the subscriptions cache when one user follows another, etc."
c.subscribe(:user_2_friends, :user_1)
20.downto(0) do |i|
base = (i*24) * 60 * 60
puts "Store a checkin"
c.event(
:key => :checkin_1,
:created_at => Time.now - base - 5 * 60,
:data => { :type => 'checkin', :id => '1', :message => 'Hello' },
:timelines => [:user_1, :spot_1],
:subscribers => [:user_1],
:objects => { :user => :user_1, :spot => :spot_1 }
)
puts "Store a pin"
c.event(
:key => :pin_1,
:created_at => Time.now - base - 10 * 60,
:data => { :type => 'pin', :id => '1' },
:timelines => [:user_1, :trip_1],
:subscribers => [:user_1],
:objects => { :user => :user_1, :trip => :trip_1 }
)
puts "Store a highlight"
c.event(
:key => :highlight_1,
:created_at => Time.now - base - 15 * 60,
:data => { :type => 'highlight', :id => '1' },
:timelines => [:user_1, :highlight_type_1],
:subscribers => [:user_1],
:objects => { :user => :user_1, :highlight_type => :highlight_type_1 }
)
puts "Store a comment"
c.event(
:key => :comment_1,
:created_at => Time.now - base - 20 * 60,
:data => { :type => 'comment', :id => '1', :message => 'Nice!' },
:objects => { :user => :user_2 },
:events => [ :checkin_1 ]
)
end
puts "Request a timeline"
puts c.timeline(:user_2_friends).to_yaml
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
gowalla-archive/chronologic | https://github.com/gowalla-archive/chronologic/blob/1fecdea9edce001e10e024fae43bf4c06f837b98/examples/privacy.rb | examples/privacy.rb | require 'chronologic'
cl = Chronologic::Client.new('http://localhost:7979')
# AK is public and friends with BF and BO
cl.subscribe('user_ak_feed', 'user_bf')
cl.subscribe('user_ak_feed', 'user_bo')
# BF is public and friends with BO and AK
cl.subscribe('user_bf_feed', 'user_bo')
cl.subscribe('user_bf_feed', 'user_ak')
# BO is private and friends with BF and AK
cl.subscribe('user_bo_feed', 'user_bf')
cl.subscribe('user_bo_feed', 'user_ak')
# BS is public shares with BO but BO does not reciprocate
cl.subscribe('user_bs_feed', 'user_bo')
# BO checks in
event = Chronologic::Event.new(
:key => 'checkin_1',
:timestamp => Time.now,
:data => {:message => "I'm here!"},
:objects => {'user' => 'user_bo', 'spot' => 'spot_1'},
:timelines => ['user_bo']
)
# TODO
# event.private = true
cl.publish(event)
# BF and AK and see BO's checkin
p cl.timeline('user_bf_home')['items'] # Should include BO's event
p cl.timeline('user_ak_home')['items'] # Should include BO's event
# BS cannot see BO's checkin
cl.timeline('user_bs_home') # Should not include BO's event
if defined?(CL::Subscriber)
## Now let's write this with a CL model
ak = CL::Subscriber.new('user_ak_home')
bf = CL::Subscriber.new('user_bf_home')
bo = CL::Subscriber.new('user_bo_home')
bs = CL::Subscriber.new('user_bs_home')
bo.subscribe_to(ak.timeline_key)
bo.subscribe_to(bf.timeline_key)
ak.subcribe_to(bo.timeline_key)
bf.subscribe_to(bo.timeline_key)
bs.subscribe_to(bo.timeline_key)
event = CL::Event.new(
:key => 'checkin_1',
:data => {:message => "I'm here!"},
:objects => {'user' => bo, 'spot' => 'spot_1'},
:timelines => [bo.timeline_key],
:private => true
)
event.publish!
ak_timeline = CL::Timeline.new(ak.feed_key)
p ak_timeline.fetch # Should include BO's event
bf_timeline = CL::Timeline.new(bf.feed_key)
p bf_timeline.fetch # Should include BO's event
bs_timeline = CL::Timeline.new(bs.feed_key)
p bs_timeline.fetch # Should _not_ include BO's event
end
| ruby | MIT | 1fecdea9edce001e10e024fae43bf4c06f837b98 | 2026-01-04T17:43:46.847213Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.