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 |
|---|---|---|---|---|---|---|---|---|
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/spec/easy_captcha_spec.rb | spec/easy_captcha_spec.rb | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe EasyCaptcha do
describe :setup do
EasyCaptcha.setup do |config|
# Cache
config.cache = false
# Chars
config.chars = %w(2 3 4 5 6 7 9 A C D E F G H J K L M N P Q R S T U X Y Z)
# Length
config.length = 6
# Image
config.image_height = 40
config.image_width = 140
# configure generator
config.generator :default do |generator|
# Font
generator.font_size = 24
generator.font_fill_color = '#333333'
generator.font_stroke_color = '#000000'
generator.font_stroke = 0
generator.font_family = File.expand_path('../../resources/afont.ttf', __FILE__)
generator.image_background_color = '#FFFFFF'
# Wave
generator.wave = true
generator.wave_length = (60..100)
generator.wave_amplitude = (3..5)
# Sketch
generator.sketch = true
generator.sketch_radius = 3
generator.sketch_sigma = 1
# Implode
generator.implode = 0.1
# Blur
generator.blur = true
generator.blur_radius = 1
generator.blur_sigma = 2
end
end
it 'sould not cache' do
EasyCaptcha.cache?.should be_false
end
it 'should have default generator' do
EasyCaptcha.generator.should be_an(EasyCaptcha::Generator::Default)
end
describe :depracations do
before do
EasyCaptcha.setup do |config|
# Length
config.length = 6
# Image
config.image_height = 40
config.image_width = 140
config.generator :default do |generator|
# Font
generator.font_size = 24
generator.font_fill_color = '#333333'
generator.font_stroke_color = '#000000'
generator.font_stroke = 0
generator.font_family = File.expand_path('../../resources/afont.ttf', __FILE__)
generator.image_background_color = '#FFFFFF'
# Wave
generator.wave = true
generator.wave_length = (60..100)
generator.wave_amplitude = (3..5)
# Sketch
generator.sketch = true
generator.sketch_radius = 3
generator.sketch_sigma = 1
# Implode
generator.implode = 0.1
# Blur
generator.blur = true
generator.blur_radius = 1
generator.blur_sigma = 2
end
end
end
it 'get config' do
[
:font_size, :font_fill_color, :font_family, :font_stroke, :font_stroke_color,
:image_background_color, :sketch, :sketch_radius, :sketch_sigma, :wave,
:wave_length, :wave_amplitude, :implode, :blur, :blur_radius, :blur_sigma
].each do |method|
EasyCaptcha.generator.send(method).should_not be_nil
end
end
it 'method_missing should call normal on non depracations' do
-> { EasyCaptcha.send('a_missing_method') }.should raise_error
end
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
begin
require 'simplecov'
SimpleCov.start 'rails'
rescue LoadError
end
require 'easy_captcha'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha.rb | lib/easy_captcha.rb | require 'rails'
require 'action_controller'
require 'active_record'
require 'active_support'
# Captcha-Plugin for Rails
module EasyCaptcha
autoload :Espeak, 'easy_captcha/espeak'
autoload :Captcha, 'easy_captcha/captcha'
autoload :CaptchaController, 'easy_captcha/captcha_controller'
autoload :ModelHelpers, 'easy_captcha/model_helpers'
autoload :ViewHelpers, 'easy_captcha/view_helpers'
autoload :ControllerHelpers, 'easy_captcha/controller_helpers'
autoload :Generator, 'easy_captcha/generator'
# Cache
mattr_accessor :cache
@@cache = false
# Cache temp
mattr_accessor :cache_temp_dir
@@cache_temp_dir = nil
# Cache size
mattr_accessor :cache_size
@@cache_size = 500
# Cache expire
mattr_accessor :cache_expire
@@cache_expire = nil
# Chars
mattr_accessor :chars
@@chars = %w(2 3 4 5 6 7 9 A C D E F G H J K L M N P Q R S T U X Y Z)
# Length
mattr_accessor :length
@@length = 6
# Length
mattr_accessor :image_width, :image_height
@@image_width = 140
@@image_height = 40
class << self
# to configure easy_captcha
# for a sample look the readme.rdoc file
def setup
yield self
end
def cache? #:nodoc:
cache
end
# select generator and configure this
def generator(generator = nil, &block)
if generator.nil?
@generator
else
generator = generator.to_s if generator.is_a? Symbol
if generator.is_a? String
generator.gsub!(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
generator = "EasyCaptcha::Generator::#{generator}".constantize
end
@generator = generator.new &block
end
end
def espeak=(state)
if state === true
@espeak = Espeak.new
else
@espeak = false
end
end
def espeak(&block)
if block_given?
@espeak = Espeak.new &block
else
@espeak ||= false
end
end
def espeak?
not espeak === false
end
# depracated
def method_missing name, *args
name = name.to_s # fix for jruby
depracations = [
:font_size, :font_fill_color, :font_family, :font_stroke, :font_stroke_color,
:image_background_color, :sketch, :sketch_radius, :sketch_sigma, :wave,
:wave_length, :wave_amplitude, :implode, :blur, :blur_radius, :blur_sigma
]
if depracations.include? name[0..-2].to_sym or depracations.include? name.to_sym
ActiveSupport::Deprecation.warn "EasyCaptcha.#{name} is deprecated."
if name[-1,1] == '='
self.generator.send(name, args.first)
else
self.generator.send(name)
end
else
super
end
end
# called by rails after initialize
def init
require 'easy_captcha/routes'
ActiveRecord::Base.send :include, ModelHelpers
ActionController::Base.send :include, ControllerHelpers
ActionView::Base.send :include, ViewHelpers
# set default generator
generator :default
end
end
end
EasyCaptcha.init
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/generators/easy_captcha/install_generator.rb | lib/generators/easy_captcha/install_generator.rb | module EasyCaptcha
module Generators #:nodoc:
class InstallGenerator < Rails::Generators::Base #:nodoc:
source_root File.expand_path("../../templates", __FILE__)
desc "Install easy_captcha"
def copy_initializer #:nodoc:
template "easy_captcha.rb", "config/initializers/easy_captcha.rb"
end
def add_devise_routes #:nodoc:
route 'captcha_route'
end
def add_after_filter #:nodoc:
inject_into_class "app/controllers/application_controller.rb", ApplicationController do
" # reset captcha code after each request for security\n after_filter :reset_last_captcha_code!\n\n"
end
end
end
end
end | ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/generators/templates/easy_captcha.rb | lib/generators/templates/easy_captcha.rb | EasyCaptcha.setup do |config|
# Cache
# config.cache = true
# Cache temp dir from Rails.root
# config.cache_temp_dir = Rails.root + 'tmp' + 'captchas'
# Cache size
# config.cache_size = 500
# Cache expire
# config.cache_expire = 1.days
# Chars
# config.chars = %w(2 3 4 5 6 7 9 A C D E F G H J K L M N P Q R S T U X Y Z)
# Length
# config.length = 6
# Image
# config.image_height = 40
# config.image_width = 140
# eSpeak
# config.espeak do |espeak|
# Amplitude, 0 to 200
# espeak.amplitude = 80..120
# Word gap. Pause between words
# espeak.gap = 80
# Pitch adjustment, 0 to 99
# espeak.pitch = 30..70
# Use voice file of this name from espeak-data/voices
# espeak.voice = nil
# end
# configure generator
# config.generator :default do |generator|
# Font
# generator.font_size = 24
# generator.font_fill_color = '#333333'
# generator.font_stroke_color = '#000000'
# generator.font_stroke = 0
# generator.font_family = File.expand_path('../../resources/afont.ttf', __FILE__)
# generator.image_background_color = "#FFFFFF"
# Wave
# generator.wave = true
# generator.wave_length = (60..100)
# generator.wave_amplitude = (3..5)
# Sketch
# generator.sketch = true
# generator.sketch_radius = 3
# generator.sketch_sigma = 1
# Implode
# generator.implode = 0.1
# Blur
# generator.blur = true
# generator.blur_radius = 1
# generator.blur_sigma = 2
# end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/version.rb | lib/easy_captcha/version.rb | module EasyCaptcha
VERSION = '0.6.5'
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/view_helpers.rb | lib/easy_captcha/view_helpers.rb | module EasyCaptcha
# helper class for ActionView
module ViewHelpers
# generate an image_tag for captcha image
def captcha_tag(*args)
options = { :alt => 'captcha', :width => EasyCaptcha.image_width, :height => EasyCaptcha.image_height }
options.merge! args.extract_options!
image_tag(captcha_url(:i => Time.now.to_i), options)
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb | lib/easy_captcha/controller_helpers.rb | module EasyCaptcha
# helper class for ActionController
module ControllerHelpers
def self.included(base) #:nodoc:
base.class_eval do
helper_method :valid_captcha?, :captcha_valid?
end
end
# generate captcha image and return it as blob
def generate_captcha
if EasyCaptcha.cache
# create cache dir
FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir)
# select all generated captchas from cache
files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png")
unless files.size < EasyCaptcha.cache_size
file = File.open(files.at(Kernel.rand(files.size)))
session[:captcha] = File.basename(file.path, '.*')
if file.mtime < EasyCaptcha.cache_expire.ago
File.unlink(file.path)
# remove speech version
File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav"))
else
return file.readlines.join
end
end
generated_code = generate_captcha_code
image = Captcha.new(generated_code).image
# write captcha for caching
File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image }
# write speech file if u create a new captcha image
EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak?
# return image
image
else
Captcha.new(generate_captcha_code).image
end
end
# generate speech by captcha from session
def generate_speech_captcha
raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak?
if EasyCaptcha.cache
File.read(speech_captcha_cache_path(current_captcha_code))
else
wav_file = Tempfile.new("#{current_captcha_code}.wav")
EasyCaptcha.espeak.generate(current_captcha_code, wav_file.path)
File.read(wav_file.path)
end
end
# return cache path of captcha image
def captcha_cache_path(code)
"#{EasyCaptcha.cache_temp_dir}/#{code}.png"
end
# return cache path of speech captcha
def speech_captcha_cache_path(code)
"#{EasyCaptcha.cache_temp_dir}/#{code}.wav"
end
# current active captcha from session
def current_captcha_code
session[:captcha]
end
# generate captcha code, save in session and return
def generate_captcha_code
session[:captcha] = EasyCaptcha.length.times.collect { EasyCaptcha.chars[rand(EasyCaptcha.chars.size)] }.join
end
# validate given captcha code and re
def captcha_valid?(code)
return false if session[:captcha].blank? or code.blank?
session[:captcha].to_s.upcase == code.to_s.upcase
end
alias_method :valid_captcha?, :captcha_valid?
# reset the captcha code in session for security after each request
def reset_last_captcha_code!
session.delete(:captcha)
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/model_helpers.rb | lib/easy_captcha/model_helpers.rb | module EasyCaptcha
module ModelHelpers #:nodoc:
# helper class for ActiveRecord
def self.included(base) #:nodoc:
base.extend ClassMethods
end
module ClassMethods #:nodoc:
# to activate model captcha validation
def acts_as_easy_captcha
include InstanceMethods
attr_writer :captcha, :captcha_verification
end
end
module InstanceMethods #:nodoc:
def captcha #:nodoc:
""
end
# validate captcha
def captcha_valid?
errors.add(:captcha, :invalid) if @captcha.blank? or @captcha_verification.blank? or @captcha.to_s.upcase != @captcha_verification.to_s.upcase
end
alias_method :valid_captcha?, :captcha_valid?
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/routes.rb | lib/easy_captcha/routes.rb | module ActionDispatch #:nodoc:
module Routing #:nodoc:
class Mapper #:nodoc:
# call to add default captcha root
def captcha_route
match 'captcha' => 'easy_captcha/captcha#captcha', :via => :get
end
end
end
end | ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/captcha_controller.rb | lib/easy_captcha/captcha_controller.rb | module EasyCaptcha
# captcha controller
class CaptchaController < ActionController::Base
before_filter :overwrite_cache_control
# captcha action send the generated image to browser
def captcha
if params[:format] == "wav" and EasyCaptcha.espeak?
send_data generate_speech_captcha, :disposition => 'inline', :type => 'audio/wav'
else
send_data generate_captcha, :disposition => 'inline', :type => 'image/png'
end
end
private
# Overwrite cache control for Samsung Galaxy S3 (remove no-store)
def overwrite_cache_control
response.headers["Cache-Control"] = "no-cache, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/generator.rb | lib/easy_captcha/generator.rb | module EasyCaptcha
# module for generators
module Generator
autoload :Base, 'easy_captcha/generator/base'
autoload :Default, 'easy_captcha/generator/default'
end
end | ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/espeak.rb | lib/easy_captcha/espeak.rb | module EasyCaptcha
# espeak wrapper
class Espeak
# generator for captcha images
def initialize(&block)
defaults
yield self if block_given?
end
# set default values
def defaults
@amplitude = 80..120
@pitch = 30..70
@gap = 80
@voice = nil
end
attr_writer :amplitude, :pitch, :gap, :voice
# return amplitude
def amplitude
if @amplitude.is_a? Range
@amplitude.to_a.sort_by { rand }.first
else
@amplitude.to_i
end
end
# return amplitude
def pitch
if @pitch.is_a? Range
@pitch.to_a.sort_by { rand }.first
else
@pitch.to_i
end
end
def gap
@gap.to_i
end
def voice
if @voice.is_a? Array
v = @voice.sort_by { rand }.first
else
v = @voice
end
v.try :gsub, /[^A-Za-z0-9\-\+]/, ""
end
# generate wav file by captcha
def generate(captcha, wav_file)
# get code
if captcha.is_a? Captcha
code = captcha.code
elsif captcha.is_a? String
code = captcha
else
raise ArgumentError, "invalid captcha"
end
# add spaces
code = code.each_char.to_a.join(" ")
cmd = "espeak -g 10"
cmd << " -a #{amplitude}" unless @amplitude.nil?
cmd << " -p #{pitch}" unless @pitch.nil?
cmd << " -g #{gap}" unless @gap.nil?
cmd << " -v '#{voice}'" unless @voice.nil?
cmd << " -w #{wav_file} '#{code}'"
%x{#{cmd}}
true
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/captcha.rb | lib/easy_captcha/captcha.rb | # encoding: utf-8
module EasyCaptcha
# captcha generation class
class Captcha
# code for captcha generation
attr_reader :code
# blob of generated captcha image
attr_reader :image
# generate captcha by code
def initialize code
@code = code
generate_captcha
end
def inspect #:nodoc:
"<EasyCaptcha::Captcha @code=#{code}>"
end
private
def generate_captcha #:nodoc:
@image = EasyCaptcha.generator.generate(@code)
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/generator/default.rb | lib/easy_captcha/generator/default.rb | # encoding: utf-8
module EasyCaptcha
module Generator
# default generator
class Default < Base
# set default values
def defaults
@font_size = 24
@font_fill_color = '#333333'
@font = File.expand_path('../../../../resources/captcha.ttf', __FILE__)
@font_stroke = '#000000'
@font_stroke_color = 0
@image_background_color = '#FFFFFF'
@sketch = true
@sketch_radius = 3
@sketch_sigma = 1
@wave = true
@wave_length = (60..100)
@wave_amplitude = (3..5)
@implode = 0.05
@blur = true
@blur_radius = 1
@blur_sigma = 2
end
# Font
attr_accessor :font_size, :font_fill_color, :font, :font_family, :font_stroke, :font_stroke_color
# Background
attr_accessor :image_background_color, :background_image
# Sketch
attr_accessor :sketch, :sketch_radius, :sketch_sigma
# Wave
attr_accessor :wave, :wave_length, :wave_amplitude
# Implode
attr_accessor :implode
# Gaussian Blur
attr_accessor :blur, :blur_radius, :blur_sigma
def sketch? #:nodoc:
@sketch
end
def wave? #:nodoc:
@wave
end
def blur? #:nodoc:
@blur
end
# generate image
def generate(code)
require 'rmagick' unless defined?(Magick)
config = self
canvas = Magick::Image.new(EasyCaptcha.image_width, EasyCaptcha.image_height) do |variable|
self.background_color = config.image_background_color unless config.image_background_color.nil?
self.background_color = 'none' if config.background_image.present?
end
# Render the text in the image
canvas.annotate(Magick::Draw.new, 0, 0, 0, 0, code) {
self.gravity = Magick::CenterGravity
self.font = config.font
self.font_weight = Magick::LighterWeight
self.fill = config.font_fill_color
if config.font_stroke.to_i > 0
self.stroke = config.font_stroke_color
self.stroke_width = config.font_stroke
end
self.pointsize = config.font_size
}
# Blur
canvas = canvas.blur_image(config.blur_radius, config.blur_sigma) if config.blur?
# Wave
w = config.wave_length
a = config.wave_amplitude
canvas = canvas.wave(rand(a.last - a.first) + a.first, rand(w.last - w.first) + w.first) if config.wave?
# Sketch
canvas = canvas.sketch(config.sketch_radius, config.sketch_sigma, rand(180)) if config.sketch?
# Implode
canvas = canvas.implode(config.implode.to_f) if config.implode.is_a? Float
# Crop image because to big after waveing
canvas = canvas.crop(Magick::CenterGravity, EasyCaptcha.image_width, EasyCaptcha.image_height)
# Combine images if background image is present
if config.background_image.present?
background = Magick::Image.read(config.background_image).first
background.composite!(canvas, Magick::CenterGravity, Magick::OverCompositeOp)
image = background.to_blob { self.format = 'PNG' }
else
image = canvas.to_blob { self.format = 'PNG' }
end
# ruby-1.9
image = image.force_encoding 'UTF-8' if image.respond_to? :force_encoding
canvas.destroy!
image
end
end
end
end
| ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
phatworx/easy_captcha | https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/generator/base.rb | lib/easy_captcha/generator/base.rb | module EasyCaptcha
module Generator
# base class for generators
class Base
# generator for captcha images
def initialize(&block)
defaults
yield self if block_given?
end
# default values for generator
def defaults
end
end
end
end | ruby | MIT | d3a0281b00bd8fc67caf15a0380e185809f12252 | 2026-01-04T17:55:31.126454Z | false |
reclaim-the-stack/actioncable-enhanced-postgresql-adapter | https://github.com/reclaim-the-stack/actioncable-enhanced-postgresql-adapter/blob/6e540411f33ec8374f290adb65d9859fadaf2ee9/test/common.rb | test/common.rb | # frozen_string_literal: true
require "concurrent"
require "active_support/core_ext/hash/indifferent_access"
require "pathname"
module CommonSubscriptionAdapterTest
WAIT_WHEN_EXPECTING_EVENT = 3
WAIT_WHEN_NOT_EXPECTING_EVENT = 0.2
def setup
server = ActionCable::Server::Base.new
server.config.cable = cable_config.with_indifferent_access
server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter_klass = server.config.pubsub_adapter
@rx_adapter = adapter_klass.new(server)
@tx_adapter = adapter_klass.new(server)
end
def teardown
[@rx_adapter, @tx_adapter].uniq.compact.each(&:shutdown)
end
def subscribe_as_queue(channel, adapter = @rx_adapter)
queue = Queue.new
callback = -> data { queue << data }
subscribed = Concurrent::Event.new
adapter.subscribe(channel, callback, Proc.new { subscribed.set })
subscribed.wait(WAIT_WHEN_EXPECTING_EVENT)
assert_predicate subscribed, :set?
yield queue
sleep WAIT_WHEN_NOT_EXPECTING_EVENT
assert_empty queue
ensure
adapter.unsubscribe(channel, callback) if subscribed.set?
end
def test_subscribe_and_unsubscribe
subscribe_as_queue("channel") do |queue|
end
end
def test_basic_broadcast
subscribe_as_queue("channel") do |queue|
@tx_adapter.broadcast("channel", "hello world")
assert_equal "hello world", queue.pop
end
end
def test_broadcast_after_unsubscribe
keep_queue = nil
subscribe_as_queue("channel") do |queue|
keep_queue = queue
@tx_adapter.broadcast("channel", "hello world")
assert_equal "hello world", queue.pop
end
@tx_adapter.broadcast("channel", "hello void")
sleep WAIT_WHEN_NOT_EXPECTING_EVENT
assert_empty keep_queue
end
def test_multiple_broadcast
subscribe_as_queue("channel") do |queue|
@tx_adapter.broadcast("channel", "bananas")
@tx_adapter.broadcast("channel", "apples")
received = []
2.times { received << queue.pop }
assert_equal ["apples", "bananas"], received.sort
end
end
def test_identical_subscriptions
subscribe_as_queue("channel") do |queue|
subscribe_as_queue("channel") do |queue_2|
@tx_adapter.broadcast("channel", "hello")
assert_equal "hello", queue_2.pop
end
assert_equal "hello", queue.pop
end
end
def test_simultaneous_subscriptions
subscribe_as_queue("channel") do |queue|
subscribe_as_queue("other channel") do |queue_2|
@tx_adapter.broadcast("channel", "apples")
@tx_adapter.broadcast("other channel", "oranges")
assert_equal "apples", queue.pop
assert_equal "oranges", queue_2.pop
end
end
end
def test_channel_filtered_broadcast
subscribe_as_queue("channel") do |queue|
@tx_adapter.broadcast("other channel", "one")
@tx_adapter.broadcast("channel", "two")
assert_equal "two", queue.pop
end
end
def test_long_identifiers
channel_1 = "a" * 100 + "1"
channel_2 = "a" * 100 + "2"
subscribe_as_queue(channel_1) do |queue|
subscribe_as_queue(channel_2) do |queue_2|
@tx_adapter.broadcast(channel_1, "apples")
@tx_adapter.broadcast(channel_2, "oranges")
assert_equal "apples", queue.pop
assert_equal "oranges", queue_2.pop
end
end
end
end
| ruby | MIT | 6e540411f33ec8374f290adb65d9859fadaf2ee9 | 2026-01-04T17:55:38.359026Z | false |
reclaim-the-stack/actioncable-enhanced-postgresql-adapter | https://github.com/reclaim-the-stack/actioncable-enhanced-postgresql-adapter/blob/6e540411f33ec8374f290adb65d9859fadaf2ee9/test/postgresql_test.rb | test/postgresql_test.rb | # frozen_string_literal: true
require_relative "test_helper"
require_relative "common"
require_relative "channel_prefix"
require "active_record"
require "action_cable/subscription_adapter/enhanced_postgresql"
class PostgresqlAdapterTest < ActionCable::TestCase
include CommonSubscriptionAdapterTest
include ChannelPrefixTest
def setup
database_config = { "adapter" => "postgresql", "database" => "actioncable_enhanced_postgresql_test" }
# Create the database unless it already exists
begin
ActiveRecord::Base.establish_connection database_config.merge("database" => "postgres")
ActiveRecord::Base.connection.create_database database_config["database"], encoding: "utf8"
rescue ActiveRecord::DatabaseAlreadyExists
end
# Connect to the database
ActiveRecord::Base.establish_connection database_config
begin
ActiveRecord::Base.connection.connect!
rescue
@rx_adapter = @tx_adapter = nil
skip "Couldn't connect to PostgreSQL: #{database_config.inspect}"
end
super
end
def teardown
super
ActiveRecord::Base.connection_handler.clear_all_connections!
end
def cable_config
{ adapter: "enhanced_postgresql", payload_encryptor_secret: SecureRandom.hex(16) }
end
def test_clear_active_record_connections_adapter_still_works
server = ActionCable::Server::Base.new
server.config.cable = cable_config.with_indifferent_access
server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter_klass = Class.new(server.config.pubsub_adapter) do
def active?
!@listener.nil?
end
end
adapter = adapter_klass.new(server)
subscribe_as_queue("channel", adapter) do |queue|
adapter.broadcast("channel", "hello world")
assert_equal "hello world", queue.pop
end
ActiveRecord::Base.connection_handler.clear_reloadable_connections!
assert adapter.active?
end
def test_default_subscription_connection_identifier
subscribe_as_queue("channel") { }
identifiers = ActiveRecord::Base.connection.exec_query("SELECT application_name FROM pg_stat_activity").rows
assert_includes identifiers, ["ActionCable-PID-#{$$}"]
end
def test_custom_subscription_connection_identifier
server = ActionCable::Server::Base.new
server.config.cable = cable_config.merge(id: "hello-world-42").with_indifferent_access
server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter = server.config.pubsub_adapter.new(server)
subscribe_as_queue("channel", adapter) { }
identifiers = ActiveRecord::Base.connection.exec_query("SELECT application_name FROM pg_stat_activity").rows
assert_includes identifiers, ["hello-world-42"]
end
# Postgres has a NOTIFY payload limit of 8000 bytes which requires special handling to avoid
# "PG::InvalidParameterValue: ERROR: payload string too long" errors.
def test_large_payload_broadcast
large_payloads_table = ActionCable::SubscriptionAdapter::EnhancedPostgresql::LARGE_PAYLOADS_TABLE
ActiveRecord::Base.connection_pool.with_connection do |connection|
connection.execute("DROP TABLE IF EXISTS #{large_payloads_table}")
end
server = ActionCable::Server::Base.new
server.config.cable = cable_config.with_indifferent_access
server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter = server.config.pubsub_adapter.new(server)
large_payload = "a" * (ActionCable::SubscriptionAdapter::EnhancedPostgresql::MAX_NOTIFY_SIZE + 1)
subscribe_as_queue("channel", adapter) do |queue|
adapter.broadcast("channel", large_payload)
# The large payload is stored in the database at this point
assert_equal 1, ActiveRecord::Base.connection.query("SELECT COUNT(*) FROM #{large_payloads_table}").first.first
assert_equal large_payload, queue.pop
end
end
def test_large_payload_escapes_correctly
large_payloads_table = ActionCable::SubscriptionAdapter::EnhancedPostgresql::LARGE_PAYLOADS_TABLE
ActiveRecord::Base.connection_pool.with_connection do |connection|
connection.execute("DROP TABLE IF EXISTS #{large_payloads_table}")
end
server = ActionCable::Server::Base.new
server.config.cable = cable_config.with_indifferent_access
server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter = server.config.pubsub_adapter.new(server)
ascii_string = (32..126).map(&:chr).join.encode("UTF-8")
expected_length = (ActionCable::SubscriptionAdapter::EnhancedPostgresql::MAX_NOTIFY_SIZE + 1)
large_payload = (ascii_string * (1.0 * expected_length/ascii_string.length).ceil)[...expected_length]
subscribe_as_queue("channel", adapter) do |queue|
adapter.broadcast("channel", large_payload)
# The large payload is stored in the database at this point
assert_equal 1, ActiveRecord::Base.connection.query("SELECT COUNT(*) FROM #{large_payloads_table}").first.first
got = queue.pop
assert_equal large_payload.length, got.length, "Expected lengths to match"
assert_equal large_payload, got, "Expected values to match"
end
end
def test_automatic_payload_deletion
inserts_per_delete = ActionCable::SubscriptionAdapter::EnhancedPostgresql::INSERTS_PER_DELETE
large_payloads_table = ActionCable::SubscriptionAdapter::EnhancedPostgresql::LARGE_PAYLOADS_TABLE
large_payload = "a" * (ActionCable::SubscriptionAdapter::EnhancedPostgresql::MAX_NOTIFY_SIZE + 1)
pg_conn = ActiveRecord::Base.connection.raw_connection
# Prep the database so that we are one insert away from a delete. All but one entry should be old
# enough to be reaped on the next broadcast.
pg_conn.exec("DROP TABLE IF EXISTS #{large_payloads_table}")
pg_conn.exec(ActionCable::SubscriptionAdapter::EnhancedPostgresql::CREATE_LARGE_TABLE_QUERY)
# Insert 98 stale payloads
(inserts_per_delete - 2).times do
pg_conn.exec("INSERT INTO #{large_payloads_table} (payload, created_at) VALUES ('a', NOW() - INTERVAL '3 minutes') RETURNING id")
end
# Insert 1 fresh payload
new_payload_id = pg_conn.exec("INSERT INTO #{large_payloads_table} (payload, created_at) VALUES ('a', NOW() - INTERVAL '1 minutes') RETURNING id").first.fetch("id")
# Sanity check that the auto incrementing ID is what we expect
assert_equal inserts_per_delete - 1, new_payload_id
server = ActionCable::Server::Base.new
server.config.cable = cable_config.with_indifferent_access
server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter = server.config.pubsub_adapter.new(server)
adapter.broadcast("channel", large_payload)
remaining_payload_ids = pg_conn.query("SELECT id FROM #{large_payloads_table} ORDER BY id").values.flatten
assert_equal [inserts_per_delete - 1, inserts_per_delete], remaining_payload_ids
ensure
pg_conn&.close
end
# Specifying url should bypass ActiveRecord and connect directly to the provided database
def test_explicit_url_configuration
large_payloads_table = ActionCable::SubscriptionAdapter::EnhancedPostgresql::LARGE_PAYLOADS_TABLE
explicit_database = "actioncable_enhanced_postgresql_test_explicit"
ActiveRecord::Base.connection_pool.with_connection do |connection|
connection.execute("CREATE DATABASE #{explicit_database}")
rescue ActiveRecord::DatabaseAlreadyExists
end
pg_conn = PG::Connection.open(dbname: explicit_database)
pg_conn.exec("DROP TABLE IF EXISTS #{large_payloads_table}")
server = ActionCable::Server::Base.new
server.config.cable = cable_config.merge(url: "postgres://localhost/#{explicit_database}").with_indifferent_access
server.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter = server.config.pubsub_adapter.new(server)
large_payload = "a" * (ActionCable::SubscriptionAdapter::EnhancedPostgresql::MAX_NOTIFY_SIZE + 1)
subscribe_as_queue("channel", adapter) do |queue|
adapter.broadcast("channel", large_payload)
# The large payload is stored in the database at this point
assert_equal "1", pg_conn.query("SELECT COUNT(*) FROM #{large_payloads_table}").first.fetch("count")
assert_equal large_payload, queue.pop
end
ensure
pg_conn&.close
end
end
| ruby | MIT | 6e540411f33ec8374f290adb65d9859fadaf2ee9 | 2026-01-04T17:55:38.359026Z | false |
reclaim-the-stack/actioncable-enhanced-postgresql-adapter | https://github.com/reclaim-the-stack/actioncable-enhanced-postgresql-adapter/blob/6e540411f33ec8374f290adb65d9859fadaf2ee9/test/channel_prefix.rb | test/channel_prefix.rb | # frozen_string_literal: true
module ChannelPrefixTest
def test_channel_prefix
server2 = ActionCable::Server::Base.new(config: ActionCable::Server::Configuration.new)
server2.config.cable = alt_cable_config.with_indifferent_access
server2.config.logger = Logger.new(StringIO.new).tap { |l| l.level = Logger::UNKNOWN }
adapter_klass = server2.config.pubsub_adapter
rx_adapter2 = adapter_klass.new(server2)
tx_adapter2 = adapter_klass.new(server2)
subscribe_as_queue("channel") do |queue|
subscribe_as_queue("channel", rx_adapter2) do |queue2|
@tx_adapter.broadcast("channel", "hello world")
tx_adapter2.broadcast("channel", "hello world 2")
assert_equal "hello world", queue.pop
assert_equal "hello world 2", queue2.pop
end
end
end
def alt_cable_config
cable_config.merge(channel_prefix: "foo")
end
end
| ruby | MIT | 6e540411f33ec8374f290adb65d9859fadaf2ee9 | 2026-01-04T17:55:38.359026Z | false |
reclaim-the-stack/actioncable-enhanced-postgresql-adapter | https://github.com/reclaim-the-stack/actioncable-enhanced-postgresql-adapter/blob/6e540411f33ec8374f290adb65d9859fadaf2ee9/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
require "debug"
require "action_cable"
require "active_support/testing/autorun"
require "active_support/testing/method_call_assertions"
require "minitest/reporters"
Minitest::Reporters.use!
# Set test adapter and logger
ActionCable.server.config.cable = { "adapter" => "test" }
ActionCable.server.config.logger = Logger.new(nil)
class ActionCable::TestCase < ActiveSupport::TestCase
include ActiveSupport::Testing::MethodCallAssertions
def wait_for_async
wait_for_executor Concurrent.global_io_executor
end
def run_in_eventmachine
yield
wait_for_async
end
def wait_for_executor(executor)
# do not wait forever, wait 2s
timeout = 2
until executor.completed_task_count == executor.scheduled_task_count
sleep 0.1
timeout -= 0.1
raise "Executor could not complete all tasks in 2 seconds" unless timeout > 0
end
end
end
| ruby | MIT | 6e540411f33ec8374f290adb65d9859fadaf2ee9 | 2026-01-04T17:55:38.359026Z | false |
reclaim-the-stack/actioncable-enhanced-postgresql-adapter | https://github.com/reclaim-the-stack/actioncable-enhanced-postgresql-adapter/blob/6e540411f33ec8374f290adb65d9859fadaf2ee9/lib/actioncable-enhanced-postgresql-adapter.rb | lib/actioncable-enhanced-postgresql-adapter.rb | require_relative "action_cable/subscription_adapter/enhanced_postgresql"
require_relative "railtie" if defined? Rails::Railtie
| ruby | MIT | 6e540411f33ec8374f290adb65d9859fadaf2ee9 | 2026-01-04T17:55:38.359026Z | false |
reclaim-the-stack/actioncable-enhanced-postgresql-adapter | https://github.com/reclaim-the-stack/actioncable-enhanced-postgresql-adapter/blob/6e540411f33ec8374f290adb65d9859fadaf2ee9/lib/railtie.rb | lib/railtie.rb | class ActionCable::SubscriptionAdapter::EnhancedPostgresql
class Railtie < ::Rails::Railtie
initializer "action_cable.enhanced_postgresql_adapter" do
ActiveSupport.on_load(:active_record) do
large_payloads_table = ActionCable::SubscriptionAdapter::EnhancedPostgresql::LARGE_PAYLOADS_TABLE
ActiveRecord::SchemaDumper.ignore_tables << large_payloads_table
end
end
end
end
| ruby | MIT | 6e540411f33ec8374f290adb65d9859fadaf2ee9 | 2026-01-04T17:55:38.359026Z | false |
reclaim-the-stack/actioncable-enhanced-postgresql-adapter | https://github.com/reclaim-the-stack/actioncable-enhanced-postgresql-adapter/blob/6e540411f33ec8374f290adb65d9859fadaf2ee9/lib/action_cable/subscription_adapter/enhanced_postgresql.rb | lib/action_cable/subscription_adapter/enhanced_postgresql.rb | # freeze_string_literal: true
require "action_cable/subscription_adapter/postgresql"
require "connection_pool"
module ActionCable
module SubscriptionAdapter
class EnhancedPostgresql < PostgreSQL
MAX_NOTIFY_SIZE = 7997 # documented as 8000 bytes, but there appears to be some overhead in transit
LARGE_PAYLOAD_PREFIX = "__large_payload:"
INSERTS_PER_DELETE = 100 # execute DELETE query every N inserts
LARGE_PAYLOADS_TABLE = "action_cable_large_payloads"
CREATE_LARGE_TABLE_QUERY = <<~SQL
CREATE UNLOGGED TABLE IF NOT EXISTS #{LARGE_PAYLOADS_TABLE} (
id SERIAL PRIMARY KEY,
payload TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
SQL
CREATE_CREATED_AT_INDEX_QUERY = <<~SQL
CREATE INDEX IF NOT EXISTS index_action_cable_large_payloads_on_created_at
ON #{LARGE_PAYLOADS_TABLE} (created_at)
SQL
INSERT_LARGE_PAYLOAD_QUERY = "INSERT INTO #{LARGE_PAYLOADS_TABLE} (payload, created_at) VALUES ($1, CURRENT_TIMESTAMP) RETURNING id"
SELECT_LARGE_PAYLOAD_QUERY = "SELECT payload FROM #{LARGE_PAYLOADS_TABLE} WHERE id = $1"
DELETE_LARGE_PAYLOAD_QUERY = "DELETE FROM #{LARGE_PAYLOADS_TABLE} WHERE created_at < CURRENT_TIMESTAMP - INTERVAL '2 minutes'"
def initialize(*)
super
@url = @server.config.cable[:url]
@connection_pool_size = @server.config.cable[:connection_pool_size] || ENV["RAILS_MAX_THREADS"] || 5
end
def broadcast(channel, payload)
channel = channel_with_prefix(channel)
with_broadcast_connection do |pg_conn|
channel = pg_conn.escape_identifier(channel_identifier(channel))
if payload.bytesize > MAX_NOTIFY_SIZE
payload_id = insert_large_payload(pg_conn, payload)
if payload_id % INSERTS_PER_DELETE == 0
pg_conn.exec(DELETE_LARGE_PAYLOAD_QUERY)
end
# Encrypt payload_id to prevent simple integer ID spoofing
encrypted_payload_id = payload_encryptor.encrypt_and_sign(payload_id)
payload = "#{LARGE_PAYLOAD_PREFIX}#{encrypted_payload_id}"
end
pg_conn.exec("NOTIFY #{channel}, #{pg_conn.escape_literal(payload)}")
end
end
def payload_encryptor
@payload_encryptor ||= begin
secret = @server.config.cable[:payload_encryptor_secret]
secret ||= Rails.application.secret_key_base if defined? Rails
secret ||= ENV["SECRET_KEY_BASE"]
raise ArgumentError, "Missing payload_encryptor_secret configuration for ActionCable EnhancedPostgresql adapter. You need to either explicitly configure it in cable.yml or set the SECRET_KEY_BASE environment variable." unless secret
secret_32_byte = Digest::SHA256.digest(secret)
ActiveSupport::MessageEncryptor.new(secret_32_byte)
end
end
def with_broadcast_connection(&block)
return super unless @url
connection_pool.with do |pg_conn|
yield pg_conn
end
end
# Called from the Listener thread
def with_subscriptions_connection(&block)
return super unless @url
pg_conn = PG::Connection.new(@url)
pg_conn.exec("SET application_name = #{pg_conn.escape_identifier(identifier)}")
yield pg_conn
ensure
pg_conn&.close
end
private
def connection_pool
@connection_pool ||= ConnectionPool.new(size: @connection_pool_size, timeout: 5) do
PG::Connection.new(@url)
end
end
def insert_large_payload(pg_conn, payload)
result = pg_conn.exec_params(INSERT_LARGE_PAYLOAD_QUERY, [payload])
result.first.fetch("id").to_i
rescue PG::UndefinedTable
pg_conn.exec(CREATE_LARGE_TABLE_QUERY)
pg_conn.exec(CREATE_CREATED_AT_INDEX_QUERY)
retry
end
# Override needed to ensure we reference our local Listener class
def listener
@listener || @server.mutex.synchronize { @listener ||= Listener.new(self, @server.event_loop) }
end
class Listener < PostgreSQL::Listener
def invoke_callback(callback, message)
if message.start_with?(LARGE_PAYLOAD_PREFIX)
encrypted_payload_id = message.delete_prefix(LARGE_PAYLOAD_PREFIX)
payload_id = @adapter.payload_encryptor.decrypt_and_verify(encrypted_payload_id)
@adapter.with_broadcast_connection do |pg_conn|
result = pg_conn.exec_params(SELECT_LARGE_PAYLOAD_QUERY, [payload_id])
message = result.first.fetch("payload")
end
end
@event_loop.post { super }
end
end
end
end
end
| ruby | MIT | 6e540411f33ec8374f290adb65d9859fadaf2ee9 | 2026-01-04T17:55:38.359026Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/rails/init.rb | rails/init.rb | Dir[File.expand_path(File.join(File.dirname(__FILE__), 'lib', '**', '*.rb'))].uniq.each do |file|
require file
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/dry_model_generator.rb | generators/dry_model/dry_model_generator.rb | require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'lib', 'dry_generator'))
class DryModelGenerator < DryGenerator
# Banner: Generator arguments and options.
BANNER_ARGS = [
"[_indexes:field,field+field,field,...]"
].freeze
BANNER_OPTIONS = [
"[--skip-timestamps]",
"[--skip-migration]"
].freeze
# Paths.
MODELS_PATH = File.join('app', 'models').freeze
MIGRATIONS_PATH = File.join('db', 'migrate').freeze
attr_reader :indexes,
:references
def initialize(runtime_args, runtime_options = {})
@options = DEFAULT_OPTIONS.merge(options)
super(runtime_args, runtime_options.merge(@options))
@attributes ||= []
args_for_model = []
@args.each do |arg|
arg_entities = arg.split(':')
if arg =~ /^#{NON_ATTR_ARG_KEY_PREFIX}/
if arg =~ /^#{NON_ATTR_ARG_KEY_PREFIX}index/
arg_indexes = arg_entities[1].split(',').compact.uniq
@indexes = arg_indexes.collect do |index|
if index =~ /\+/
index.split('+').collect { |i| i.downcase.to_sym }
else
index.downcase.to_sym
end
end
end
else
@attributes << Rails::Generator::GeneratedAttribute.new(*arg_entities)
args_for_model << arg
end
end
@args = args_for_model
@references = attributes.select(&:reference?)
end
def manifest
record do |m|
# Check for class naming collisions.
m.class_collisions class_name, "#{class_name}Test"
# Model.
m.directory File.join(MODELS_PATH, class_path)
m.template File.join('models', 'active_record_model.rb'),
File.join(MODELS_PATH, class_path, "#{file_name}.rb")
# Model Tests.
unless options[:skip_tests]
model_tests_path = File.join(TEST_PATHS[test_framework], UNIT_TESTS_PATH[test_framework])
m.directory File.join(model_tests_path, class_path)
m.template File.join('models', 'tests', "#{test_framework}", 'unit_test.rb'),
File.join(model_tests_path, class_path, "#{file_name}_#{TEST_POST_FIX[test_framework]}.rb")
# Fixtures/Factories.
if options[:fixtures]
fixtures_path = File.join(TEST_PATHS[test_framework], 'fixtures')
m.directory File.join(fixtures_path, class_path)
m.template File.join('models', 'fixture_data', 'active_record_fixtures.yml'),
File.join(fixtures_path, class_path, "#{table_name}.yml")
end
if options[:factory_girl]
factory_girl_path = File.join(TEST_PATHS[test_framework], 'factories')
m.directory File.join(factory_girl_path, class_path)
m.template File.join('models', 'fixture_data', 'factory_girl_factories.rb'),
File.join(factory_girl_path, class_path, "#{plural_name}.rb")
end
if options[:machinist]
machinist_path = File.join(TEST_PATHS[test_framework], 'blueprints')
m.directory File.join(machinist_path, class_path)
m.template File.join('models', 'fixture_data', 'machinist_blueprints.rb'),
File.join(machinist_path, class_path, "#{plural_name}.rb")
end
# NOTE: :object_daddy handled in model
end
# Migration.
unless options[:skip_migration]
m.migration_template File.join('models', 'active_record_migration.rb'), MIGRATIONS_PATH,
:assigns => {:migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}"},
:migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}"
end
end
end
protected
def add_options!(opt)
super(opt)
opt.separator ' '
opt.separator 'Model Options:'
opt.on("--skip-timestamps", "Don't add timestamps to the migration file.") do |v|
options[:skip_timestamps] = v
end
opt.on("--skip-migration", "Skip generation of migration file.") do |v|
options[:skip_migration] = v
end
opt.on("--skip-tests", "Skip generation of tests.") do |v|
options[:skip_tests] = v
end
opt.separator ' '
end
def banner_args
[BANNER_ARGS, super].flatten.join(' ')
end
def banner_options
[BANNER_OPTIONS, super].flatten.join(' ')
end
def banner
[super, banner_args, banner_options].join(' ')
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/prototypes/active_record_model.rb | generators/dry_model/prototypes/active_record_model.rb | class Duck < ActiveRecord::Base
belongs_to :owner
# object_daddy
generator_for(:name) { "AString" }
generator_for(:description) { "SomeText" }
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/prototypes/active_record_migration.rb | generators/dry_model/prototypes/active_record_migration.rb | class CreateDucks < ActiveRecord::Migration
def self.up
create_table :resources, :force => true do |t|
t.string :name
t.text :description
t.timestamps
end
add_index :resources, :name
add_index :resources, [:name, :description]
end
def self.down
drop_table :resources
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/prototypes/tests/rspec/unit_test.rb | generators/dry_model/prototypes/tests/rspec/unit_test.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe DuckTest do
fixtures :ducks
it "should be valid" do
DuckTest.new.should be_valid
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/prototypes/tests/shoulda/unit_test.rb | generators/dry_model/prototypes/tests/shoulda/unit_test.rb | require 'test_helper'
class DuckTest < ActiveRecord::TestCase
fixtures :ducks
should_have_db_column :name
should_have_db_column :description
context "A test context" do
setup do
end
should 'test something' do
assert true
end
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/prototypes/tests/test_unit/unit_test.rb | generators/dry_model/prototypes/tests/test_unit/unit_test.rb | require 'test_helper'
class DuckTest < ActiveRecord::TestCase
fixtures :ducks
setup do
end
test 'something' do
assert true
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/prototypes/fixture_data/factory_girl_factories.rb | generators/dry_model/prototypes/fixture_data/factory_girl_factories.rb | Factory.define :duck, :class => Duck do |f|
f.name "AString"
f.description "SomeText"
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/prototypes/fixture_data/machinist_blueprints.rb | generators/dry_model/prototypes/fixture_data/machinist_blueprints.rb | Sham.define do
end
Resource.blueprint do
name { "AString" }
description { "SomeText" }
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/templates/models/active_record_model.rb | generators/dry_model/templates/models/active_record_model.rb | class <%= class_name %> < ActiveRecord::Base
<% unless references.empty? -%>
<% references.each do |attribute| -%>
belongs_to :<%= attribute.name %>
<% end -%>
<% end -%>
<% if options[:object_daddy] -%>
<% attributes.each do |attribute| -%>
generator_for(:<%= attribute.name %>) { <%= attribute.default_for_factory %> }
<% end -%>
<% end -%>
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/templates/models/active_record_migration.rb | generators/dry_model/templates/models/active_record_migration.rb | class <%= migration_name %> < ActiveRecord::Migration
def self.up
create_table :<%= table_name %> do |t|
<% attributes.each do |attribute| -%>
t.<%= attribute.type %> :<%= attribute.name %>
<% end -%>
<% unless options[:skip_timestamps] -%>
t.timestamps
<% end -%>
end
<% unless indexes.blank? -%>
<% indexes.each do |index| -%>
add_index :<%= table_name %>, <%= index.is_a?(Array) ? "[:#{index.join(', :')}]" : ":#{index}" %>
<% end -%>
<% end -%>
end
def self.down
drop_table :<%= table_name %>
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/templates/models/tests/rspec/unit_test.rb | generators/dry_model/templates/models/tests/rspec/unit_test.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe <%= class_name %> do
<% if options[:fixtures] -%>
fixtures :<%= table_name %>
<% end -%>
it "should be valid" do
<%= class_name %>.new.should be_valid
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/templates/models/tests/shoulda/unit_test.rb | generators/dry_model/templates/models/tests/shoulda/unit_test.rb | require 'test_helper'
class <%= class_name %>Test < ActiveRecord::TestCase
<% if options[:fixtures] -%>
fixtures :<%= plural_name %>
<% end -%>
<% attributes.each do |attribute| -%>
should_have_db_column :<%= attribute.name %>
<% end -%>
context "A test context" do
setup do
end
should 'test something' do
assert true
end
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/templates/models/tests/test_unit/unit_test.rb | generators/dry_model/templates/models/tests/test_unit/unit_test.rb | require 'test_helper'
class <%= class_name %>Test < ActiveRecord::TestCase
<% if options[:fixtures] -%>
fixtures :<%= table_name %>
<% end -%>
setup do
end
test 'something' do
assert true
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/templates/models/fixture_data/factory_girl_factories.rb | generators/dry_model/templates/models/fixture_data/factory_girl_factories.rb | Factory.define :<%= singular_name %>, :class => <%= class_name %> do |f|
<% attributes.each do |attribute| -%>
f.<%= attribute.name %> <%= attribute.default_for_factory %>
<% end -%>
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_model/templates/models/fixture_data/machinist_blueprints.rb | generators/dry_model/templates/models/fixture_data/machinist_blueprints.rb | Sham.define do
end
<%= class_name %>.blueprint do
<% attributes.each do |attribute| -%>
<%= attribute.name %> { <%= attribute.default_for_factory %> }
<% end -%>
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dmodel/dmodel_generator.rb | generators/dmodel/dmodel_generator.rb | require File.join(File.dirname(__FILE__), '..', 'dry_model', 'dry_model_generator')
class DmodelGenerator < DryModelGenerator
def initialize(runtime_args, runtime_options = {})
super
# Make Rails look for templates within generator "dry_model" path
@source_root = options[:source] || File.join(spec.path, '..', 'dry_model', 'templates')
end
def usage_message
File.read(File.join(spec.path, '..', 'dry_model', 'USAGE')) rescue ''
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/dry_scaffold_generator.rb | generators/dry_scaffold/dry_scaffold_generator.rb | require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'lib', 'dry_generator'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'dry_model', 'dry_model_generator'))
class DryScaffoldGenerator < DryGenerator
# Banner: Generator arguments and options.
BANNER_ARGS = [
"[_actions:new,create,...]",
"[_formats:html,json,...]",
DryModelGenerator::BANNER_ARGS
].freeze
BANNER_OPTIONS = [
"[--skip-pagination]",
"[--skip-resourceful]",
"[--skip-formtastic]",
"[--skip-views]",
"[--skip-builders]",
"[--skip-helpers]",
"[--layout]",
DryModelGenerator::BANNER_OPTIONS
].freeze
# Paths.
CONTROLLERS_PATH = File.join('app', 'controllers').freeze
HELPERS_PATH = File.join('app', 'helpers').freeze
VIEWS_PATH = File.join('app', 'views').freeze
LAYOUTS_PATH = File.join(VIEWS_PATH, 'layouts').freeze
ROUTES_FILE_PATH = File.join(RAILS_ROOT, 'config', 'routes.rb').freeze
# Formats.
DEFAULT_RESPOND_TO_FORMATS = [:html, :xml, :json].freeze
ENHANCED_RESPOND_TO_FORMATS = [:yml, :yaml, :txt, :text, :atom, :rss].freeze
RESPOND_TO_FEED_FORMATS = [:atom, :rss].freeze
# Actions.
DEFAULT_MEMBER_ACTIONS = [:show, :new, :edit, :create, :update, :destroy].freeze
DEFAULT_MEMBER_AUTOLOAD_ACTIONS = (DEFAULT_MEMBER_ACTIONS - [:new, :create])
DEFAULT_COLLECTION_ACTIONS = [:index].freeze
DEFAULT_COLLECTION_AUTOLOAD_ACTIONS = DEFAULT_COLLECTION_ACTIONS
DEFAULT_CONTROLLER_ACTIONS = (DEFAULT_COLLECTION_ACTIONS + DEFAULT_MEMBER_ACTIONS)
DEFAULT_VIEW_TEMPLATE_FORMAT = :haml
RESOURCEFUL_COLLECTION_NAME = 'collection'.freeze
RESOURCEFUL_SINGULAR_NAME = 'resource'.freeze
# :{action} => [:{partial}, ...]
ACTION_VIEW_TEMPLATES = {
:index => [:item],
:show => [],
:new => [:form],
:edit => [:form]
}.freeze
ACTION_FORMAT_BUILDERS = {
:index => [:atom, :rss]
}
attr_reader :controller_name,
:controller_class_path,
:controller_file_path,
:controller_class_nesting,
:controller_class_nesting_depth,
:controller_class_name,
:controller_underscore_name,
:controller_singular_name,
:controller_plural_name,
:collection_name,
:model_singular_name,
:model_plural_name,
:view_template_format,
:actions,
:formats,
:config
alias_method :controller_file_name, :controller_underscore_name
alias_method :controller_table_name, :controller_plural_name
def initialize(runtime_args, runtime_options = {})
@options = DEFAULT_OPTIONS.merge(options)
super(runtime_args, runtime_options.merge(@options))
@controller_name = @name.pluralize
base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@controller_name)
@controller_class_name_without_nesting, @controller_underscore_name, @controller_plural_name = inflect_names(base_name)
@controller_singular_name = base_name.singularize
if @controller_class_nesting.empty?
@controller_class_name = @controller_class_name_without_nesting
else
@controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
end
@view_template_format = options[:view_template_format] || DEFAULT_VIEW_TEMPLATE_FORMAT
@attributes ||= []
@args_for_model ||= []
# Non-attribute args, i.e. "_actions:new,create".
@args.each do |arg|
arg_entities = arg.split(':')
if arg =~ /^#{NON_ATTR_ARG_KEY_PREFIX}/
if arg =~ /^#{NON_ATTR_ARG_KEY_PREFIX}action/
# Replace quantifiers with default actions.
arg_entities[1].gsub!(/\*/, DEFAULT_CONTROLLER_ACTIONS.join(','))
arg_entities[1].gsub!(/new\+/, [:new, :create].join(','))
arg_entities[1].gsub!(/edit\+/, [:edit, :update].join(','))
arg_actions = arg_entities[1].split(',').compact.uniq
@actions = arg_actions.collect { |action| action.downcase.to_sym }
elsif arg =~ /^#{NON_ATTR_ARG_KEY_PREFIX}(format|respond_to)/
# Replace quantifiers with default respond_to-formats.
arg_entities[1].gsub!(/\*/, DEFAULT_RESPOND_TO_FORMATS.join(','))
arg_formats = arg_entities[1].split(',').compact.uniq
@formats = arg_formats.collect { |format| format.downcase.to_sym }
elsif arg =~ /^#{NON_ATTR_ARG_KEY_PREFIX}index/
@args_for_model << arg
end
else
@attributes << Rails::Generator::GeneratedAttribute.new(*arg_entities)
@args_for_model << arg
end
end
@actions ||= DEFAULT_ARGS[:actions] || DEFAULT_CONTROLLER_ACTIONS
@formats ||= DEFAULT_ARGS[:formats] || DEFAULT_RESPOND_TO_FORMATS
end
def manifest
record do |m|
# Check for class naming collisions.
m.class_collisions "#{controller_class_name}Controller", "#{controller_class_name}ControllerTest"
m.class_collisions "#{controller_class_name}Helper", "#{controller_class_name}HelperTest"
# Controllers.
controller_template = options[:resourceful] ? 'inherited_resources' : 'action'
m.directory File.join(CONTROLLERS_PATH, controller_class_path)
m.template File.join('controllers', "#{controller_template}_controller.rb"),
File.join(CONTROLLERS_PATH, controller_class_path, "#{controller_file_name}_controller.rb")
# Controller Tests.
unless options[:skip_tests] || options[:skip_controller_tests]
controller_tests_path = File.join(TEST_PATHS[test_framework], FUNCTIONAL_TESTS_PATH[test_framework])
m.directory File.join(controller_tests_path, controller_class_path)
m.template File.join('controllers', 'tests', "#{test_framework}", 'functional_test.rb'),
File.join(controller_tests_path, controller_class_path, "#{controller_file_name}_controller_#{TEST_POST_FIX[test_framework]}.rb")
end
# Helpers.
unless options[:skip_helpers]
m.directory File.join(HELPERS_PATH, controller_class_path)
m.template File.join('helpers', 'helper.rb'),
File.join(HELPERS_PATH, controller_class_path, "#{controller_file_name}_helper.rb")
# Helper Tests
unless options[:skip_tests]
helper_tests_path = File.join(TEST_PATHS[test_framework], 'helpers')
m.directory File.join(helper_tests_path, controller_class_path)
m.template File.join('helpers', 'tests', "#{test_framework}", 'unit_test.rb'),
File.join(helper_tests_path, controller_class_path, "#{controller_file_name}_helper_#{TEST_POST_FIX[test_framework]}.rb")
end
end
# Views.
unless options[:skip_views]
m.directory File.join(VIEWS_PATH, controller_class_path, controller_file_name)
# View template for each action.
(actions & ACTION_VIEW_TEMPLATES.keys).each do |action|
m.template File.join('views', "#{view_template_format}", "#{action}.html.#{view_template_format}"),
File.join(VIEWS_PATH, controller_file_name, "#{action}.html.#{view_template_format}")
# View template for each partial - if not already copied.
(ACTION_VIEW_TEMPLATES[action] || []).each do |partial|
m.template File.join('views', "#{view_template_format}", "_#{partial}.html.#{view_template_format}"),
File.join(VIEWS_PATH, controller_file_name, "_#{partial}.html.#{view_template_format}")
end
end
end
# Builders.
unless options[:skip_builders]
m.directory File.join(VIEWS_PATH, controller_class_path, controller_file_name)
(actions & ACTION_FORMAT_BUILDERS.keys).each do |action|
(formats & ACTION_FORMAT_BUILDERS[action] || []).each do |format|
m.template File.join('views', 'builder', "#{action}.#{format}.builder"),
File.join(VIEWS_PATH, controller_file_name, "#{action}.#{format}.builder")
end
end
end
# Layout.
if options[:layout]
m.directory File.join(LAYOUTS_PATH)
m.template File.join('views', "#{view_template_format}", "layout.html.#{view_template_format}"),
File.join(LAYOUTS_PATH, "#{controller_file_name}.html.#{view_template_format}")
end
# Routes.
unless resource_route_exists?
# TODO: Override Rails default method to not generate route if it's already defined.
m.route_resources controller_file_name
end
# Models - use Rails default generator.
m.dependency 'dry_model', [name] + @args_for_model, options.merge(:collision => :skip)
end
end
### Fixture/Factory Helpers.
def build_object
case options[:factory_framework]
when :factory_girl then
"Factory(:#{singular_name})"
when :machinist then
"#{class_name}.make"
when :object_daddy then
"#{class_name}.generate"
else #:fixtures
"#{table_name}(:basic)"
end
end
### Link Helpers.
def collection_instance
options[:resourceful] ? "#{collection_name}" : "@#{collection_name}"
end
def resource_instance
options[:resourceful] ? "#{singular_name}" : "@#{singular_name}"
end
def index_path
"#{collection_name}_path"
end
def new_path
"new_#{singular_name}_path"
end
def show_path(object_name = resource_instance)
"#{singular_name}_path(#{object_name})"
end
def edit_path(object_name = resource_instance)
"edit_#{show_path(object_name)}"
end
def destroy_path(object_name = resource_instance)
"#{object_name}"
end
def index_url
"#{collection_name}_url"
end
def new_url
"new_#{singular_name}_url"
end
def show_url(object_name = resource_instance)
"#{singular_name}_url(#{object_name})"
end
def edit_url(object_name = resource_instance)
"edit_#{show_url(object_name)}"
end
def destroy_url(object_name = resource_instance)
"#{object_name}"
end
### Feed Helpers.
def feed_link(format)
case format
when :atom then
":href => #{plural_name}_url(:#{format}), :rel => 'self'"
when :rss then
"#{plural_name}_url(#{singular_name}, :#{format})"
end
end
def feed_entry_link(format)
case format
when :atom then
":href => #{singular_name}_url(#{singular_name}, :#{format})"
when :rss then
"#{singular_name}_url(#{singular_name}, :#{format})"
end
end
def feed_date(format)
case format
when :atom then
"(#{collection_instance}.first.created_at rescue Time.now.utc).strftime('%Y-%m-%dT%H:%M:%SZ')"
when :rss then
"(#{collection_instance}.first.created_at rescue Time.now.utc).to_s(:rfc822)"
end
end
def feed_entry_date(format)
case format
when :atom then
"#{singular_name}.try(:updated_at).strftime('%Y-%m-%dT%H:%M:%SZ')"
when :rss then
"#{singular_name}.try(:updated_at).to_s(:rfc822)"
end
end
protected
def resource_route_exists?
route_exp = "map.resources :#{controller_file_name}"
File.read(ROUTES_FILE_PATH) =~ /(#{route_exp.strip}|#{route_exp.strip.tr('\'', '\"')})/
end
def assign_names!(name)
super(name)
@model_singular_name = @singular_name
@model_plural_name = @plural_name
@collection_name = options[:resourceful] ? RESOURCEFUL_COLLECTION_NAME : @model_plural_name
@singular_name = options[:resourceful] ? RESOURCEFUL_SINGULAR_NAME : @model_singular_name
@plural_name = options[:resourceful] ? RESOURCEFUL_SINGULAR_NAME.pluralize : @model_plural_name
end
def add_options!(opt)
super(opt)
### CONTROLLER + VIEW + HELPER
opt.separator ' '
opt.separator 'Scaffold Options:'
opt.on('--skip-resourceful',
"Controller: Skip 'inherited_resources' style controllers and views. Requires gem 'josevalim-inherited_resources'.") do |v|
options[:resourceful] = !v
end
opt.on('--skip-pagination',
"Controller/View: Skip 'will_paginate' for collections in controllers and views. Requires gem 'mislav-will_paginate'.") do |v|
options[:pagination] = !v
end
opt.on('--skip-formtastic',
"View: Skip 'formtastic' style forms. Requires gem 'justinfrench-formtastic'.") do |v|
options[:formtastic] = !v
end
opt.on("--skip-controller-tests", "Controller: Skip generation of tests for controller.") do |v|
options[:skip_controller_tests] = v
end
opt.on('--skip-views', "View: Skip generation of views.") do |v|
options[:skip_views] = v
end
opt.on('--skip-builders', "View: Skip generation of builders.") do |v|
options[:skip_builders] = v
end
opt.on('--layout', "View: Generate layout.") do |v|
options[:layout] = v
end
opt.on('--skip-helper', "Helper: Skip generation of helpers.") do |v|
options[:skip_helpers] = v
end
### MODEL
opt.separator ' '
opt.separator 'Model Options:'
opt.on("--skip-timestamps", "Model: Don't add timestamps to the migration file.") do |v|
options[:skip_timestamps] = v
end
opt.on("--skip-migration", "Model: Skip generation of migration file.") do |v|
options[:skip_migration] = v
end
opt.on("--skip-tests", "Model: Skip generation of tests.") do |v|
options[:skip_tests] = v
end
opt.on("--skip-controller tests", "Controller: Skip generation of tests for controller.") do |v|
options[:skip_controller_tests] = v
end
opt.separator ' '
end
def banner_args
[BANNER_ARGS, super].flatten.join(' ')
end
def banner_options
[BANNER_OPTIONS, super].flatten.join(' ')
end
def banner
[super, banner_args, banner_options].join(' ')
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/helpers/helper.rb | generators/dry_scaffold/prototypes/helpers/helper.rb | module DucksHelper
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/helpers/tests/rspec/unit_test.rb | generators/dry_scaffold/prototypes/helpers/tests/rspec/unit_test.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe DucksHelperTest
it 'should do something' do
assert true
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/helpers/tests/shoulda/unit_test.rb | generators/dry_scaffold/prototypes/helpers/tests/shoulda/unit_test.rb | require 'test_helper'
class DucksHelperTest < ActionView::TestCase
should 'test something' do
assert true
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/helpers/tests/test_unit/unit_test.rb | generators/dry_scaffold/prototypes/helpers/tests/test_unit/unit_test.rb | require 'test_helper'
class DucksHelperTest < ActionView::TestCase
test 'something' do
assert true
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/controllers/action_controller.rb | generators/dry_scaffold/prototypes/controllers/action_controller.rb | class DucksController < ApplicationController
before_filter :load_resource, :only => [:show, :edit, :update, :destroy]
before_filter :load_and_paginate_resource, :only => [:index]
# GET /ducks
# GET /ducks.xml
# GET /ducks.json
def index
respond_to do |format|
format.html # index.html.haml
#format.js # index.js.rjs
format.xml { render :xml => @ducks }
format.json { render :json => @ducks }
format.atom # index.atom.builder
format.rss # index.rss.builder
end
end
# GET /ducks/:id
# GET /ducks/:id.xml
# GET /ducks/:id.json
def show
respond_to do |format|
format.html # show.html.haml
#format.js # show.js.rjs
format.xml { render :xml => @duck }
format.json { render :json => @duck }
end
end
# GET /ducks/new
# GET /ducks/new.xml
# GET /ducks/new.json
def new
@duck = Duck.new
respond_to do |format|
format.html # new.html.haml
#format.js # new.js.rjs
format.xml { render :xml => @duck }
format.json { render :json => @duck }
end
end
# GET /ducks/:id/edit
def edit
end
# POST /ducks
# POST /ducks.xml
# POST /ducks.json
def create
@duck = Duck.new(params[:duck])
respond_to do |format|
if @duck.save
flash[:notice] = "Duck was successfully created."
format.html { redirect_to(@duck) }
#format.js # create.js.rjs
format.xml { render :xml => @duck, :status => :created, :location => @duck }
format.json { render :json => @duck, :status => :created, :location => @duck }
else
flash[:error] = "Duck could not be created."
format.html { render 'new' }
#format.js # create.js.rjs
format.xml { render :xml => @duck.errors, :status => :unprocessable_entity }
format.json { render :json => @duck.errors, :status => :unprocessable_entity }
end
end
end
# PUT /ducks/:id
# PUT /ducks/:id.xml
# PUT /ducks/:id.json
def update
respond_to do |format|
if @duck.update_attributes(params[:duck])
flash[:notice] = "Duck was successfully updated."
format.html { redirect_to(@duck) }
#format.js # update.js.rjs
format.xml { head :ok }
format.json { head :ok }
else
flash[:error] = "Duck could not be updated."
format.html { render 'edit' }
#format.js # update.js.rjs
format.xml { render :xml => @duck.errors, :status => :unprocessable_entity }
format.json { render :json => @duck.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /ducks/:id
# DELETE /ducks/:id.xml
# DELETE /ducks/:id.json
def destroy
respond_to do |format|
if @duck.destroy
flash[:notice] = "Duck was successfully destroyed."
format.html { redirect_to(ducks_url) }
#format.js # destroy.js.rjs
format.xml { head :ok }
format.json { head :ok }
else
flash[:error] = "Duck could not be destroyed."
format.html { redirect_to(duck_url(@duck)) }
#format.js # destroy.js.rjs
format.xml { head :unprocessable_entity }
format.json { head :unprocessable_entity }
end
end
end
# GET /ducks/custom_action
def custom_action
end
protected
def collection
paginate_options ||= {}
paginate_options[:page] ||= (params[:page] || 1)
paginate_options[:per_page] ||= (params[:per_page] || 20)
@collection = @ducks ||= Duck.paginate(paginate_options)
end
alias :load_and_paginate_ducks :collection
def resource
@resource = @duck = ||= Duck.find(params[:id])
end
alias :load_resource :resource
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/controllers/inherited_resources_controller.rb | generators/dry_scaffold/prototypes/controllers/inherited_resources_controller.rb | class DucksController < InheritedResources::Base
actions :index, :show, :new, :create, :edit, :update, :destroy
respond_to :html, :xml, :json
respond_to :atom, :rss, :only => [:index]
# GET /ducks/custom_action
def custom_action
end
protected
def collection
paginate_options ||= {}
paginate_options[:page] ||= (params[:page] || 1)
paginate_options[:per_page] ||= (params[:per_page] || 20)
@collection = @ducks ||= end_of_association_chain.paginate(paginate_options)
end
def resource
@resource = @duck ||= end_of_association_chain.find(params[:id])
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/controllers/tests/rspec/functional_test.rb | generators/dry_scaffold/prototypes/controllers/tests/rspec/functional_test.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe DucksController do
fixtures :all
integrate_views
it "index action should render index template" do
get :index
response.should render_template(:index)
end
it "show action should render show template" do
get :show, :id => Duck.first
response.should render_template(:show)
end
it "new action should render new template" do
get :new
response.should render_template(:new)
end
it "create action should render new template when model is invalid" do
Duck.any_instance.stubs(:valid?).returns(false)
post :create
response.should render_template(:new)
end
it "create action should redirect when model is valid" do
Duck.any_instance.stubs(:valid?).returns(true)
post :create
response.should redirect_to(duck_url(assigns[:duck]))
end
it "edit action should render edit template" do
get :edit, :id => Duck.first
response.should render_template(:edit)
end
it "update action should render edit template when model is invalid" do
Duck.any_instance.stubs(:valid?).returns(false)
put :update, :id => Duck.first
response.should render_template(:edit)
end
it "update action should redirect when model is valid" do
Duck.any_instance.stubs(:valid?).returns(true)
put :update, :id => Duck.first
response.should redirect_to(duck_url(assigns[:duck]))
end
it "destroy action should destroy model and redirect to index action" do
duck = Duck.first
delete :destroy, :id => duck
response.should redirect_to(ducks_url)
Duck.exists?(duck.id).should be_false
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/controllers/tests/shoulda/functional_test.rb | generators/dry_scaffold/prototypes/controllers/tests/shoulda/functional_test.rb | require 'test_helper'
class DucksControllerTest < ActionController::TestCase
context 'create' do
context 'with success' do
setup do
Duck.any_instance.expects(:save).returns(true)
@duck = Factory(:duck)
post :create, :duck => @duck.attributes
@duck = Resource.find(:all).last
end
should_assign_to flash[:notice]
should_redirect_to 'duck_path(@duck)'
end
context 'with failure' do
setup do
Duck.any_instance.expects(:save).returns(false)
@duck = Factory(:duck)
post :create, :duck => @duck.attributes
@duck = Resource.find(:all).last
end
should_assign_to flash[:error]
should_render_template :new
end
end
context 'update' do
context 'with success' do
setup do
Duck.any_instance.expects(:save).returns(true)
@duck = Factory(:duck)
put :update, :id => @duck.to_param, :duck => @duck.attributes
end
should_assign_to flash[:notice]
should_redirect_to 'duck_path(@duck)'
end
context 'with failure' do
setup do
Duck.any_instance.expects(:save).returns(false)
@duck = Factory(:duck)
put :update, :id => @duck.to_param, :duck => @duck.attributes
end
should_assign_to flash[:error]
should_render_template :edit
end
end
context 'destroy' do
context 'with success' do
setup do
Duck.any_instance.expects(:destroy).returns(true)
@duck = Factory(:duck)
delete :destroy, :id => @duck.to_param
end
should_assign_to flash[:notice]
should_redirect_to 'ducks_path'
end
# Not possible: destroy with failure
end
context 'new' do
setup do
get :new
end
should_respond_with :success
should_render_template :new
should_assign_to :duck
end
context 'edit' do
setup do
@duck = Factory(:duck)
get :edit, :id => @duck.to_param
end
should_respond_with :success
should_render_template :edit
should_assign_to :duck
end
context 'show' do
setup do
@duck = Factory(:duck)
get :show, :id => @duck.to_param
end
should_respond_with :success
should_render_template :show
should_assign_to :duck
end
context 'index' do
setup do
get :index
end
should_respond_with :success
should_assign_to :ducks
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/prototypes/controllers/tests/test_unit/functional_test.rb | generators/dry_scaffold/prototypes/controllers/tests/test_unit/functional_test.rb | require 'test_helper'
class DucksControllerTest < ActionController::TestCase
test 'create' do
Duck.any_instance.expects(:save).returns(true)
@duck = ducks(:basic)
post :create, :duck => @duck.attributes
assert_not_nil flash[:notice]
assert_response :redirect
end
test 'create with failure' do
Duck.any_instance.expects(:save).returns(false)
@duck = ducks(:basic)
post :create, :duck => @duck.attributes
assert_not_nil flash[:error]
assert_template 'new'
end
test 'update' do
Duck.any_instance.expects(:save).returns(true)
@duck = ducks(:basic)
put :update, :id => @duck.to_param, :duck => @duck.attributes
assert_not_nil flash[:notice]
assert_response :redirect
end
test 'update with failure' do
Duck.any_instance.expects(:save).returns(false)
@duck = ducks(:basic)
put :update, :id => @duck.to_param, :duck => @duck.attributes
assert_not_nil flash[:error]
assert_template 'edit'
end
test 'destroy' do
Duck.any_instance.expects(:destroy).returns(true)
@duck = ducks(:basic)
delete :destroy, :id => @duck.to_param
assert_not_nil flash[:notice]
assert_response :redirect
end
# Not possible: destroy with failure
test 'new' do
get :new
assert_response :success
end
test 'edit' do
@duck = ducks(:basic)
get :edit, :id => @duck.to_param
assert_response :success
end
test 'show' do
@duck = ducks(:basic)
get :show, :id => @duck.to_param
assert_response :success
end
test 'index' do
get :index
assert_response :success
assert_not_nil assigns(:ducks)
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/helpers/helper.rb | generators/dry_scaffold/templates/helpers/helper.rb | module <%= controller_class_name %>Helper
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/helpers/tests/rspec/unit_test.rb | generators/dry_scaffold/templates/helpers/tests/rspec/unit_test.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe <%= controller_class_name %>Helper do
it 'should do something' do
assert true
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/helpers/tests/shoulda/unit_test.rb | generators/dry_scaffold/templates/helpers/tests/shoulda/unit_test.rb | require 'test_helper'
class <%= controller_class_name %>HelperTest < ActionView::TestCase
should 'test something' do
assert true
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/helpers/tests/test_unit/unit_test.rb | generators/dry_scaffold/templates/helpers/tests/test_unit/unit_test.rb | require 'test_helper'
class <%= controller_class_name %>HelperTest < ActionView::TestCase
test 'something' do
assert true
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/controllers/action_controller.rb | generators/dry_scaffold/templates/controllers/action_controller.rb | class <%= controller_class_name %>Controller < ApplicationController
<% if actions -%>
before_filter :load_resource, :only => [<%= symbol_array_to_expression(actions & DryScaffoldGenerator::DEFAULT_MEMBER_AUTOLOAD_ACTIONS) %>]
<% end -%>
<% if actions -%>
before_filter :load_and_paginate_resources, :only => [<%= symbol_array_to_expression(actions & DryScaffoldGenerator::DEFAULT_COLLECTION_AUTOLOAD_ACTIONS) %>]
<% end -%>
<% if actions.include?(:index) -%>
<% formats.each do |_format| -%>
# GET /<%= plural_name %><%= ".#{_format}" unless _format == :html %>
<% end -%>
def index
respond_to do |format|
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html # index.html.haml
<% when :js then -%>
format.js # index.js.rjs
<% when :xml, :json then -%>
format.<%= _format %> { render :<%= _format %> => @<%= plural_name %> }
<% when :yml, :yaml then -%>
format.yaml { render :text => @<%= plural_name %>.to_yaml, :content_type => :'text/yaml' }
<% when :txt, :text then -%>
format.txt { render :text => @<%= plural_name %>.to_s, :content_type => :text }
<% when :atom, :rss then -%>
<% unless options[:skip_builders] -%>
format.<%= _format %> # index.<%= _format %>.builder
<% else -%>
format.<%= _format %> { }
<% end -%>
<% else -%>
format.<%= _format %> { }
<% end -%>
<% end -%>
end
end
<% end -%>
<% if actions.include?(:show) -%>
<% formats.each do |_format| -%>
# GET /<%= plural_name %>/:id<%= ".#{_format}" unless _format == :html %>
<% end -%>
def show
respond_to do |format|
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html # show.html.haml
<% when :js then -%>
format.js # show.js.rjs
<% when :xml, :json then -%>
format.<%= _format %> { render :<%= _format %> => @<%= plural_name %> }
<% when :yml, :yaml then -%>
format.yaml { render :text => @<%= plural_name %>.to_yaml, :content_type => :'text/yaml' }
<% when :txt, :text then -%>
format.txt { render :text => @<%= plural_name %>.to_s, :content_type => :text }
<% else -%>
format.<%= _format %> { }
<% end -%>
<% end -%>
end
end
<% end -%>
<% if actions.include?(:new) -%>
<% formats.each do |_format| -%>
# GET /<%= plural_name %>/new<%= ".#{_format}" unless _format == :html %>
<% end -%>
def new
<%= resource_instance %> = <%= class_name %>.new
respond_to do |format|
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html # new.html.haml
<% when :js then -%>
format.js # new.js.rjs
<% when :xml, :json then -%>
format.<%= _format %> { render :<%= _format %> => <%= resource_instance %> }
<% when :yml, :yaml then -%>
format.yaml { render :text => <%= resource_instance %>.to_yaml, :content_type => :'text/yaml' }
<% when :txt, :text then -%>
format.txt { render :text => <%= resource_instance %>.to_s, :content_type => :text }
<% else -%>
format.<%= _format %> { }
<% end -%>
<% end -%>
end
end
<% end -%>
<% if actions.include?(:edit) -%>
# GET /<%= plural_name %>/:id/edit
def edit
end
<% end -%>
<% if actions.include?(:create) -%>
<% formats.each do |_format| -%>
# POST /<%= plural_name %><%= ".#{_format}" unless _format == :html %>
<% end -%>
def create
<%= resource_instance %> = <%= class_name %>.new(params[:<%= singular_name %>])
respond_to do |format|
if <%= resource_instance %>.save
flash[:notice] = "<%= singular_name.humanize %> was successfully created."
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html { redirect_to(<%= resource_instance %>) }
<% when :js then -%>
format.js # create.js.rjs
<% when :xml, :json then -%>
format.<%= _format %> { render :<%= _format %> => <%= resource_instance %>, :status => :created, :location => <%= resource_instance %> }
<% when :yml, :yaml then -%>
format.yaml { render :text => <%= resource_instance %>.to_yaml, :content_type => :'text/yaml', :status => :created, :location => <%= resource_instance %> }
<% when :txt, :text then -%>
format.txt { render :text => <%= resource_instance %>.to_s, :content_type => :text, :status => :created, :location => <%= resource_instance %> }
<% else -%>
format.<%= _format %> { }
<% end -%>
<% end -%>
else
flash[:error] = "<%= singular_name.humanize %> could not be created."
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html { render 'new' }
<% when :js then -%>
format.js # create.js.rjs
<% when :xml, :json then -%>
format.<%= _format %> { render :<%= _format %> => <%= resource_instance %>.errors, :status => :unprocessable_entity }
<% when :yml, :yaml then -%>
format.yaml { render :text => <%= resource_instance %>.errors.to_yaml, :content_type => :'text/yaml', :status => :unprocessable_entity }
<% when :txt, :text then -%>
format.txt { render :text => <%= resource_instance %>.errors.to_s, :content_type => :text, :status => :unprocessable_entity }
<% else -%>
format.<%= _format %> { }
<% end -%>
<% end -%>
end
end
end
<% end -%>
<% if actions.include?(:update) -%>
<% formats.each do |_format| -%>
# PUT /<%= plural_name %>/:id<%= ".#{_format}" unless _format == :html %>
<% end -%>
def update
respond_to do |format|
if <%= resource_instance %>.update_attributes(params[:<%= singular_name %>])
flash[:notice] = "<%= singular_name.humanize %> was successfully updated."
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html { redirect_to(<%= resource_instance %>) }
<% when :js then -%>
format.js # update.js.rjs
<% when :xml, :json, :yml, :yaml, :txt, :text then -%>
format.<%= _format %> { head :ok }
<% else -%>
format.<%= _format %> { head :ok }
<% end -%>
<% end -%>
else
flash[:error] = "<%= singular_name.humanize %> could not be updated."
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html { render 'edit' }
<% when :js then -%>
format.js # update.js.rjs
<% when :xml, :json then -%>
format.<%= _format %> { render :<%= _format %> => <%= resource_instance %>.errors, :status => :unprocessable_entity }
<% when :yml, :yaml then -%>
format.yaml { render :text => <%= resource_instance %>.errors.to_yaml, :status => :unprocessable_entity }
<% when :txt, :text then -%>
format.txt { render :text => <%= resource_instance %>.errors.to_s, :status => :unprocessable_entity }
<% else -%>
format.<%= _format %> { head :unprocessable_entity }
<% end -%>
<% end -%>
end
end
end
<% end -%>
<% if actions.include?(:destroy) -%>
<% formats.each do |_format| -%>
# DELETE /<%= plural_name %>/:id<%= ".#{_format}" unless _format == :html %>
<% end -%>
def destroy
respond_to do |format|
if <%= resource_instance %>.destroy
flash[:notice] = "<%= singular_name.humanize %> was successfully destroyed."
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html { redirect_to(<%= plural_name %>_url) }
<% when :js then -%>
format.js # destroy.js.rjs
<% when :xml, :json, :yml, :yaml, :txt, :text then -%>
format.<%= _format %> { head :ok }
<% else -%>
format.<%= _format %> { head :ok }
<% end -%>
<% end -%>
else
flash[:error] = "<%= singular_name.humanize %> could not be destroyed."
<% formats.each do |_format| -%>
<% case _format when :html then -%>
format.html { redirect_to(<%= singular_name %>_url(<%= resource_instance %>)) }
<% when :js then -%>
format.js # destroy.js.rjs
<% when :xml, :json, :yml, :yaml, :txt, :text then -%>
format.<%= _format %> { head :unprocessable_entity }
<% else -%>
format.<%= _format %> { head :unprocessable_entity }
<% end -%>
<% end -%>
end
end
end
<% end -%>
<% (actions - DryScaffoldGenerator::DEFAULT_CONTROLLER_ACTIONS).each do |action| -%>
# GET /<%= plural_name %>/<%= action.to_s %>
def <%= action.to_s %>
end
<% end -%>
protected
def collection
<% if options[:pagination] -%>
paginate_options ||= {}
paginate_options[:page] ||= (params[:page] || 1)
paginate_options[:per_page] ||= (params[:per_page] || 20)
@collection = @<%= plural_name %> ||= <%= class_name %>.paginate(paginate_options)
<% else -%>
@collection = @<%= plural_name %> ||= <%= class_name %>.all
<% end -%>
end
alias :load_and_paginate_resources :collection
def resource
@resource = <%= resource_instance %> ||= <%= class_name %>.find(params[:id])
end
alias :load_resource :resource
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/controllers/inherited_resources_controller.rb | generators/dry_scaffold/templates/controllers/inherited_resources_controller.rb | class <%= controller_class_name %>Controller < InheritedResources::Base
<% if actions -%>
actions <%= symbol_array_to_expression(actions) %>
<% end -%>
<% if formats -%>
respond_to <%= symbol_array_to_expression(formats) %>
<% end -%>
<% (actions - DryScaffoldGenerator::DEFAULT_CONTROLLER_ACTIONS).each do |action| -%>
# GET /<%= plural_name %>/<%= action.to_s %>
def <%= action.to_s %>
end
<% end -%>
<% if options[:pagination] -%>
protected
def collection
paginate_options ||= {}
paginate_options[:page] ||= (params[:page] || 1)
paginate_options[:per_page] ||= (params[:per_page] || 20)
@<%= model_plural_name %> ||= end_of_association_chain.paginate(paginate_options)
end
<% end %>
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/controllers/tests/rspec/functional_test.rb | generators/dry_scaffold/templates/controllers/tests/rspec/functional_test.rb | require File.dirname(__FILE__) + '/../spec_helper'
describe <%= controller_class_name %>Controller do
<% if options[:fixtures] -%>
fixtures :all
<% end -%>
integrate_views
<% unless options[:factory_framework]==:fixtures %>
before(:each) do
<%= build_object %>
end
<% end %>
<% if actions.include?(:index) -%>
it "index action should render index template" do
get :index
response.should render_template(:index)
end
<% end %>
<% if actions.include?(:show) -%>
it "show action should render show template" do
get :show, :id => <%= class_name %>.first
response.should render_template(:show)
end
<% end %>
<% if actions.include?(:new) -%>
it "new action should render new template" do
get :new
response.should render_template(:new)
end
<% end %>
<% if actions.include?(:create) -%>
it "create action should render new template when model is invalid" do
<%= class_name %>.any_instance.stubs(:valid?).returns(false)
post :create
response.should render_template(:new)
end
it "create action should redirect when model is valid" do
<%= class_name %>.any_instance.stubs(:valid?).returns(true)
post :create
response.should redirect_to(<%= singular_name %>_url(assigns[:<%= singular_name %>]))
end
<% end %>
<% if actions.include?(:edit) -%>
it "edit action should render edit template" do
get :edit, :id => <%= class_name %>.first
response.should render_template(:edit)
end
<% end %>
<% if actions.include?(:update) -%>
it "update action should render edit template when model is invalid" do
<%= class_name %>.any_instance.stubs(:valid?).returns(false)
put :update, :id => <%= class_name %>.first
response.should render_template(:edit)
end
it "update action should redirect when model is valid" do
<%= class_name %>.any_instance.stubs(:valid?).returns(true)
put :update, :id => <%= class_name %>.first
response.should redirect_to(<%= singular_name %>_url(assigns[:<%= singular_name %>]))
end
<% end %>
<% if actions.include?(:destroy) -%>
it "destroy action should destroy model and redirect to index action" do
<%= singular_name %> = <%= class_name %>.first
delete :destroy, :id => <%= singular_name %>
response.should redirect_to(<%= plural_name %>_url)
<%= class_name %>.exists?(<%= singular_name %>.id).should be_false
end
<% end %>
<% (actions - DryScaffoldGenerator::DEFAULT_CONTROLLER_ACTIONS).each do |action| -%>
it '<%= action.to_s %> action should render <%= action.to_s %> template' do
get :<%= action.to_s %>
response.should render_template(:<%= action.to_s %>)
end
<% end -%>
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/controllers/tests/shoulda/functional_test.rb | generators/dry_scaffold/templates/controllers/tests/shoulda/functional_test.rb | require 'test_helper'
class <%= controller_class_name %>ControllerTest < ActionController::TestCase
<% if actions.include?(:create) -%>
context 'create' do
setup do
<%= resource_instance %> = <%= build_object %>
post :create, :<%= singular_name %> => <%= resource_instance %>.attributes
<%= resource_instance %> = <%= class_name %>.find(:all).last
end
should_redirect_to("the <%= resource_instance %>'s show page") { <%= show_path %> }
end
<% end -%>
<% if actions.include?(:update) -%>
context 'update' do
setup do
<%= resource_instance %> = <%= build_object %>
put :update, :id => <%= resource_instance %>.to_param, :<%= singular_name %> => <%= resource_instance %>.attributes
end
should_redirect_to("the <%= resource_instance %>'s show page") { <%= show_path %> }
end
<% end -%>
<% if actions.include?(:destroy) -%>
context 'destroy' do
setup do
<%= resource_instance %> = <%= build_object %>
delete :destroy, :id => <%= resource_instance %>.to_param
end
should_redirect_to("the <%= resource_instance %>'s index page") { <%= index_path %> }
end
<% end -%>
<% if actions.include?(:new) -%>
context 'new' do
setup do
get :new
end
should_respond_with :success
should_render_template :new
should_assign_to :<%= singular_name %>
end
<% end -%>
<% if actions.include?(:edit) -%>
context 'edit' do
setup do
<%= resource_instance %> = <%= build_object %>
get :edit, :id => <%= resource_instance %>.to_param
end
should_respond_with :success
should_render_template :edit
should_assign_to :<%= singular_name %>
end
<% end -%>
<% if actions.include?(:show) -%>
context 'show' do
setup do
<%= resource_instance %> = <%= build_object %>
get :show, :id => <%= resource_instance %>.to_param
end
should_respond_with :success
should_render_template :show
should_assign_to :<%= singular_name %>
end
<% end -%>
<% if actions.include?(:index) -%>
context 'index' do
setup do
get :index
end
should_respond_with :success
should_assign_to :<%= plural_name %>
end
<% end -%>
<% (actions - DryScaffoldGenerator::DEFAULT_CONTROLLER_ACTIONS).each do |action| -%>
context '<%= action.to_s %>' do
setup do
get :<%= action.to_s %>
end
should_respond_with :success
end
<% end -%>
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dry_scaffold/templates/controllers/tests/test_unit/functional_test.rb | generators/dry_scaffold/templates/controllers/tests/test_unit/functional_test.rb | require 'test_helper'
class <%= controller_class_name %>ControllerTest < ActionController::TestCase
<% if actions.include?(:create) -%>
test 'create' do
<%= class_name %>.any_instance.expects(:save).returns(true)
<%= resource_instance %> = <%= build_object %>
post :create, :<%= singular_name %> => <%= resource_instance %>.attributes
assert_response :redirect
end
test 'create with failure' do
<%= class_name %>.any_instance.expects(:save).returns(false)
<%= resource_instance %> = <%= build_object %>
post :create, :<%= singular_name %> => <%= resource_instance %>.attributes
assert_template 'new'
end
<% end -%>
<% if actions.include?(:update) -%>
test 'update' do
<%= class_name %>.any_instance.expects(:save).returns(true)
<%= resource_instance %> = <%= build_object %>
put :update, :id => <%= build_object %>.to_param, :<%= singular_name %> => <%= resource_instance %>.attributes
assert_response :redirect
end
test 'update with failure' do
<%= class_name %>.any_instance.expects(:save).returns(false)
<%= resource_instance %> = <%= build_object %>
put :update, :id => <%= build_object %>.to_param, :<%= singular_name %> => <%= resource_instance %>.attributes
assert_template 'edit'
end
<% end -%>
<% if actions.include?(:destroy) -%>
test 'destroy' do
<%= class_name %>.any_instance.expects(:destroy).returns(true)
<%= resource_instance %> = <%= build_object %>
delete :destroy, :id => <%= resource_instance %>.to_param
assert_not_nil flash[:notice]
assert_response :redirect
end
# Not possible: destroy with failure
<% end -%>
<% if actions.include?(:new) -%>
test 'new' do
get :new
assert_response :success
end
<% end -%>
<% if actions.include?(:edit) -%>
test 'edit' do
<%= resource_instance %> = <%= build_object %>
get :edit, :id => <%= resource_instance %>.to_param
assert_response :success
end
<% end -%>
<% if actions.include?(:show) -%>
test 'show' do
<%= resource_instance %> = <%= build_object %>
get :show, :id => <%= resource_instance %>.to_param
assert_response :success
end
<% end -%>
<% if actions.include?(:index) -%>
test 'index' do
get :index
assert_response :success
assert_not_nil assigns(:<%= table_name %>)
end
<% end -%>
<% (actions - DryScaffoldGenerator::DEFAULT_CONTROLLER_ACTIONS).each do |action| -%>
test '<%= action.to_s %>' do
get :<%= action.to_s %>
assert_response :success
end
<% end -%>
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/generators/dscaffold/dscaffold_generator.rb | generators/dscaffold/dscaffold_generator.rb | require File.join(File.dirname(__FILE__), '..', 'dry_scaffold', 'dry_scaffold_generator')
class DscaffoldGenerator < DryScaffoldGenerator
def initialize(runtime_args, runtime_options = {})
super
# Make Rails look for templates within generator "dry_scaffold" path
@source_root = options[:source] || File.join(spec.path, '..', 'dry_scaffold', 'templates')
end
def usage_message
File.read(File.join(spec.path, '..', 'dry_scaffold', 'USAGE')) rescue ''
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/lib/setup_helper.rb | lib/setup_helper.rb | module SetupHelper
# Add gem configuration to a specified Rails environment file
def config_gems(config_file, gems)
sentinel = 'Rails::Initializer.run do |config|'
config_line = ''
gems.each do |gem|
gem_info = gem.to_s.split('-')
if gem_info.size > 1
gem_owner = gem_info[0]
gem_lib = gem_info[1]
config_line = "config.gem '#{gem_owner}-#{gem_lib}', :lib => '#{gem_lib}'"
else
gem_lib = gem_info[0]
config_line = "config.gem '#{gem_lib}'"
end
gsub_file_if_missing config_file, /(#{Regexp.escape(sentinel)})/mi, config_line do |match|
"#{match}\n #{config_line}"
end
end
end
# Add info to specified file and beneath specified regex if the expression don't exist in the file.
def gsub_file_if_missing(path, regexp, new_exp, *args, &block)
existing_content = File.read(path)
unless existing_content =~ /(#{new_exp.strip}|#{new_exp.strip.tr('\'', '\"')})/
content = File.read(path).gsub(regexp, *args, &block)
else
content = existing_content
end
File.open(path, 'wb') { |file| file.write(content) }
end
end | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/lib/dry_generator.rb | lib/dry_generator.rb |
class DryGenerator < Rails::Generator::NamedBase
HAS_WILL_PAGINATE = defined?(WillPaginate)
HAS_FORMTASTIC = defined?(Formtastic)
HAS_INHERITED_RESOURCES = defined?(InheritedResources)
HAS_SHOULDA = defined?(Shoulda)
HAS_RSPEC = defined?(Rspec)
# Load defaults from config file - default or custom.
begin
default_config_file = File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'scaffold.yml'))
custom_config_file = File.expand_path(File.join(Rails.root, 'config', 'scaffold.yml'))
config_file = File.join(File.exist?(custom_config_file) ? custom_config_file : default_config_file)
config = YAML::load(File.open(config_file))
CONFIG_ARGS = config['dry_scaffold']['args'] rescue nil
CONFIG_OPTIONS = config['dry_scaffold']['options'] rescue nil
end
# Banner: Generator arguments and options.
BANNER_ARGS = [
"[field:type field:type ...]"
].freeze
BANNER_OPTIONS = [
"[--skip-tests]",
"[--shoulda]",
"[--rspec]",
"[--fixtures]",
"[--fgirl]",
"[--machinist]",
"[--odaddy]"
].freeze
DEFAULT_ARGS = {
:actions => (CONFIG_ARGS['actions'].split(',').compact.uniq.collect { |v| v.downcase.to_sym } rescue nil),
:formats => (CONFIG_ARGS['formats'].split(',').compact.uniq.collect { |v| v.downcase.to_sym } rescue nil)
}.freeze
DEFAULT_OPTIONS = {
:resourceful => CONFIG_OPTIONS['resourceful'] || HAS_INHERITED_RESOURCES,
:formtastic => CONFIG_OPTIONS['formtastic'] || HAS_FORMTASTIC,
:pagination => CONFIG_OPTIONS['pagination'] || HAS_WILL_PAGINATE,
:skip_tests => !CONFIG_OPTIONS['tests'] || false,
:skip_controller_tests => !CONFIG_OPTIONS['controller_tests'] || false,
:skip_helpers => !CONFIG_OPTIONS['helpers'] || false,
:skip_views => !CONFIG_OPTIONS['views'] || false,
:layout => CONFIG_OPTIONS['layout'] || false,
:fixtures => CONFIG_OPTIONS['fixtures'] || false,
:factory_girl => CONFIG_OPTIONS['factory_girl'] || CONFIG_OPTIONS['fgirl'] || false,
:machinist => CONFIG_OPTIONS['machinist'] || false,
:object_daddy => CONFIG_OPTIONS['object_daddy'] || CONFIG_OPTIONS['odaddy'] || false,
:test_unit => CONFIG_OPTIONS['test_unit'] || CONFIG_OPTIONS['tunit'] || false,
:shoulda => CONFIG_OPTIONS['shoulda'] || false,
:rspec => CONFIG_OPTIONS['rspec'] || false
}.freeze
TEST_PATHS = {
:test_unit => 'test',
:shoulda => 'test',
:rspec => 'spec'
}.freeze
TEST_POST_FIX = {
:test_unit => 'test',
:shoulda => 'test',
:rspec => 'spec'
}.freeze
DEFAULT_TEST_FRAMEWORK = :test_unit
DEFAULT_FACTORY_FRAMEWORK = :fixtures
TESTS_PATH = File.join('test').freeze
FUNCTIONAL_TESTS_PATH = {
:test_unit => 'functional',
:shoulda => 'functional',
:rspec => 'controllers'
}
UNIT_TESTS_PATH = {
:test_unit => 'unit',
:shoulda => 'unit',
:rspec => 'models',
}
CUSTOM_TEMPLATES_PATH = Rails.root.join(*%w[lib scaffold_templates])
NON_ATTR_ARG_KEY_PREFIX = '_'.freeze
attr_accessor :view_template_format,
:test_framework,
:factory_framework
def initialize(runtime_args, runtime_options = {})
super(runtime_args, runtime_options)
set_test_framework
end
def source_path(relative_source)
custom_relative_source = File.join('lib', 'scaffold_templates', relative_source)
custom_source = Rails.root.join(custom_relative_source)
puts " custom @#{custom_relative_source}" if File.exist?(custom_relative_source)
File.exist?(custom_source) ? custom_source : super(relative_source)
end
protected
def set_test_framework
@test_framework = (options[:test_framework] && options[:test_framework].to_sym) ||
[:rspec, :test_unit, :shoulda].detect{ |t| options[t] } ||
DEFAULT_TEST_FRAMEWORK
end
def symbol_array_to_expression(array)
":#{array.compact.join(', :')}" if array.present?
end
def banner_args
BANNER_ARGS.join(' ')
end
def banner_options
BANNER_OPTIONS.join(' ')
end
def banner
"\nUsage: \n\n#{$0} #{spec.name} MODEL_NAME"
end
def add_options!(opt)
opt.separator ' '
opt.separator 'Scaffold + Model Options:'
opt.on('--skip-tests', "Test: Skip generation of tests.") do |v|
options[:skip_tests] = v
end
opt.on("--tunit", "Test: Generate \"test_unit\" tests. Note: Rails default.") do |v|
options[:test_unit] = v
options[:test_framework] = :test_unit
end
opt.on("--shoulda", "Test: Generate \"shoulda\" tests.") do |v|
options[:shoulda] = v
options[:test_framework] = :shoulda
end
opt.on("--rspec", "Test: Generate \"rspec\" tests.") do |v|
options[:rspec] = v
options[:test_framework] = :rspec
end
opt.on("--fixtures", "Test: Generate fixtures. Note: Rails default.") do |v|
options[:fixtures] = v
options[:factory_framework] = :fixtures
end
opt.on("--fgirl", "Test: Generate \"factory_girl\" factories.") do |v|
options[:factory_girl] = v
options[:factory_framework] = :factory_girl
end
opt.on("--machinist", "Test: Generate \"machinist\" blueprints (factories).") do |v|
options[:machinist] = v
options[:factory_framework] = :machinist
end
opt.on("--odaddy", "Test: Generate \"object_daddy\" generator/factory methods.") do |v|
options[:object_daddy] = v
options[:factory_framework] = :object_daddy
end
end
end
module Rails
module Generator
class GeneratedAttribute
def default_for_fixture
@default ||= case type
when :integer then 1
when :float then 1.5
when :decimal then '9.99'
when :datetime, :timestamp, :time then Time.now.to_s(:db)
when :date then Date.today.to_s(:db)
when :string then 'Hello'
when :text then 'Lorem ipsum dolor sit amet...'
when :boolean then false
else
''
end
end
def default_for_factory
@default ||= case type
when :integer then 1
when :float then 1.5
when :decimal then '9.99'
when :datetime, :timestamp, :time then 'Time.now'
when :date then 'Date.today'
when :string then '"Hello"'
when :text then '"Lorem ipsum dolor sit amet..."'
when :boolean then false
else
''
end
end
end
end
end
| ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
grimen/dry_scaffold | https://github.com/grimen/dry_scaffold/blob/7b54d447b4043d70cde6bfb316f2f4c0aecc37ad/lib/dry_scaffold/tasks.rb | lib/dry_scaffold/tasks.rb | require 'rubygems'
require 'rake'
# Make tasks visible for Rails also when used as gem.
load File.expand_path(File.join(File.dirname(__FILE__), *%w(.. .. tasks dry_scaffold.rake))) | ruby | MIT | 7b54d447b4043d70cde6bfb316f2f4c0aecc37ad | 2026-01-04T17:55:39.642122Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/test_helper.rb | test/test_helper.rb | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'worque'
require 'timecop'
require 'minitest/autorun'
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/acceptance_test.rb | test/acceptance_test.rb | require 'test_helper'
require 'worque'
require 'thor/runner'
require 'webmock/minitest'
require 'json'
describe Worque do
describe 'todo' do
before do
$stdout = StringIO.new
end
after do
system "rm -rf tmp/*"
end
it 'creates a notes for today' do
date = Date.new(2016, 7, 14)
Timecop.freeze(date) do
ARGV.replace %w[todo --path tmp/for/test]
Worque::CLI.start
assert_equal("tmp/for/test/notes-2016-07-14.md", $stdout.string.strip)
end
end
it 'creates a notes for yesterday' do
date = Date.new(2016, 7, 14)
Timecop.freeze(date) do
ARGV.replace %w[todo --for yesterday --path tmp/for/test]
Worque::CLI.start
assert_equal("tmp/for/test/notes-2016-07-13.md", $stdout.string.strip)
end
end
it 'creates a notes for tomorrow' do
date = Date.new(2016, 7, 14)
Timecop.freeze(date) do
ARGV.replace %w[todo --for tomorrow --path tmp/for/test]
Worque::CLI.start
assert_equal("tmp/for/test/notes-2016-07-15.md", $stdout.string.strip)
end
end
it 'creates a notes for last friday if today is Monday and skip weekend is set' do
date = Date.new(2016, 7, 18)
Timecop.freeze(date) do
ARGV.replace %w[todo --for=yesterday --path tmp/for/test]
Worque::CLI.start
assert_equal("tmp/for/test/notes-2016-07-15.md", $stdout.string.strip)
end
end
it 'creates a notes for sunday if today is Monday and NO skip weekend is set' do
date = Date.new(2016, 7, 18)
Timecop.freeze(date) do
ARGV.replace %w[todo --for yesterday --no-skip-weekend --path tmp/for/test]
Worque::CLI.start
assert_equal("tmp/for/test/notes-2016-07-17.md", $stdout.string.strip)
end
end
it 'append task to notes' do
date = Date.new(2016, 7, 24)
Timecop.freeze(date) do
ARGV.replace %w[todo --path tmp/for/test --append-task "foo"]
Worque::CLI.start
assert_equal("tmp/for/test/notes-2016-07-24.md\n", $stdout.string)
end
end
it 'should notify user when path is not set' do
begin
$stderr = StringIO.new
Worque::Command::Todo::Action.run({})
rescue Worque::InvalidPath => e
assert_equal('Neither --path nor WORQUE_PATH is not set', e.message)
ensure
$stderr = IO.for_fd(2)
end
end
describe '~/.worquerc exists' do
it 'takes ~/.worquerc by default' do
date = Date.new(2016, 7, 14)
Timecop.freeze(date) do
File.stub(:read, {path: 'tmp/test'}.to_json) do
ARGV.replace %w[todo]
Worque::CLI.start
assert_equal("tmp/test/notes-2016-07-14.md\n", $stdout.string)
end
end
end
end
end
describe 'push' do
before do
@path = '/tmp/test'
@today = Date.new(2016, 7, 14)
Timecop.freeze(@today) do
Worque::Command::Todo::Action.run(path: @path, for: 'today')
end
$stdout = StringIO.new
$stderr = StringIO.new
end
it 'raises error if no channel specified' do
date = Date.new(2016, 7, 14)
Timecop.freeze(date) do
ARGV.replace %w[push]
Worque::CLI.start
assert_equal("No value provided for required options '--channel'", $stderr.string.strip)
end
end
describe 'channel are specified' do
it 'pushes the notes today to Slack channel' do
stubbed_result = {
"ok"=>true,
"channel"=>"secret",
"ts"=>"1469116417.000010",
"message" => {
"type"=>"message",
"user"=>"U02G4HZSH",
"text"=>"Hello World from the other side",
"bot_id"=>"secret",
"ts"=>"1469116417.000010"
}
}.to_json
stub_request(:post, "https://slack.com/api/chat.postMessage").
to_return(:status => 200, :body => stubbed_result, :headers => {})
stub_request(:post, "http://slack.com:443/api/chat.postMessage").
to_return(:status => 200, :body => stubbed_result, :headers => {})
date = Date.new(2016, 7, 14)
Timecop.freeze(date) do
ARGV.replace ["push", "--path=#{@path}", "--channel=hello"]
Worque::CLI.start
result = JSON.parse($stdout.string.strip)
assert(result['ok'])
end
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/version_test.rb | test/lib/worque/version_test.rb | require 'test_helper'
describe Worque::VERSION do
it 'has version set' do
refute_nil Worque::VERSION
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/command/push/options_test.rb | test/lib/worque/command/push/options_test.rb | require 'test_helper'
describe Worque::Command::Push::Options do
describe '#initialize' do
it 'accepts mass assignments' do
opts = Worque::Command::Push::Options.new(channel: 'test', for: 'tomorrow', token: 'secret')
assert_equal 'secret', opts.token
assert_equal 'test', opts.channel
assert_equal 'tomorrow', opts.for
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/command/push/action_test.rb | test/lib/worque/command/push/action_test.rb | require 'test_helper'
require 'webmock/minitest'
describe Worque::Command::Push::Action do
let(:action) { Worque::Command::Push::Action }
before do
# Clean up tmp directory
options = { path: 'tmp/hello/world', for: 'today' }
ENV['SLACK_API_TOKEN'] = 'test-token'
Worque::Command::Todo::Action.run(options)
# Stub Slack API call
stubbed_result = {
"ok"=>true,
"channel"=>"secret",
"ts"=>"1469116417.000010",
"message" => {
"type"=>"message",
"user"=>"U02G4HZSH",
"text"=>"Hello World from the other side",
"bot_id"=>"secret",
"ts"=>"1469116417.000010"
}
}.to_json
stub_request(:post, "http://slack.com:443/api/chat.postMessage").
to_return(status: 200, body: stubbed_result, headers: {})
stub_request(:post, "https://slack.com/api/chat.postMessage").
to_return(status: 200, body: stubbed_result, headers: {})
end
after { system('rm -rf tmp/*') }
describe '#call' do
it 'pushes the file to Slack' do
result = action.run(path: 'tmp/hello/world/', channel: 'test', for: 'today')
assert(result['ok'])
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/command/todo/options_test.rb | test/lib/worque/command/todo/options_test.rb | require 'test_helper'
describe Worque::Command::Todo::Options do
describe '#initialize' do
it 'accepts mass assignments' do
opts = Worque::Command::Todo::Options.new(path: 'tmp', skip_weekend: true, for: 'tomorrow')
assert_equal 'tmp', opts.path
assert opts.skip_weekend?
assert_equal 'tomorrow', opts.for
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/command/todo/action_test.rb | test/lib/worque/command/todo/action_test.rb | require 'test_helper'
describe Worque::Command::Todo::Action do
after do
# Clean up tmp directory
system('rm -rf tmp/*')
end
let(:action) { Worque::Command::Todo::Action }
describe '#call' do
describe 'when directory does not exist' do
it 'creates the directory' do
options = { path: 'tmp/hello/word', for: 'today' }
action.run(options)
assert File.exists?(options[:path])
end
end
describe 'when mode is yesterday' do
it 'creates the file for yesterday' do
options = { path: 'tmp/hello/word', for: :yesterday }
Timecop.freeze(Date.new(2016, 7, 15)) do
action.run(options)
assert File.exists?("#{options[:path]}/notes-2016-07-14.md")
end
end
end
describe 'when mode is adding task' do
it 'append task title to notes' do
options = { path: 'tmp/hello/word', for: 'today', append_task: 'foo' }
Timecop.freeze(Date.new(2016, 7, 24)) do
action.run(options)
assert File.exists?("#{options[:path]}/notes-2016-07-24.md")
assert File.readlines("#{options[:path]}/notes-2016-07-24.md").grep(/foo/).any?
end
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/utils/command_test.rb | test/lib/worque/utils/command_test.rb | require 'test_helper'
describe Worque::Utils::Command do
before do
@helper = Worque::Utils::Command
system('rm -rf tmp/*')
end
after do
system('rm -rf tmp/*')
end
describe '.mkdir' do
it 'makes new dir' do
path = "#{ Dir.pwd }/tmp/hello/world"
@helper.mkdir(path)
assert Dir.exists?(path)
end
describe 'no permission' do
it 'raises error' do
path = '/some/path/not/allowed'
assert_raises do
@helper.mkdir(path)
end
assert !Dir.exists?(path)
end
end
end
describe '.touch' do
it 'creates file if it does not exist' do
dir = 'tmp'
@helper.mkdir(dir)
path = 'tmp/text.txt'
@helper.touch(path)
assert File.exists?(path)
end
end
describe '.append_text' do
it 'append text to file' do
dir = 'tmp'
@helper.mkdir(dir)
path = 'tmp/text.txt'
@helper.touch(path)
text = 'foo'
@helper.append_text(path, text)
assert File.readlines(path).grep(/#{text}/).any?
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/utils/business_day_test.rb | test/lib/worque/utils/business_day_test.rb | require 'test_helper'
require 'date'
describe Worque::Utils::BusinessDay do
before do
@helper = Worque::Utils::BusinessDay
end
describe '.next' do
it 'returns the next day' do
thursday = Date.new(2016, 7, 14)
assert_equal 5, @helper.next(thursday).wday
end
it 'skips weekend by default' do
friday = Date.new(2016, 7, 15)
assert_equal 1, @helper.next(friday).wday
end
it 'does not skip weekend if skip_weekend is set' do
friday = Date.new(2016, 7, 15)
assert_equal 6, @helper.next(friday, false).wday
end
end
describe '.previous' do
it 'returns the previous day' do
thursday = Date.new(2016, 7, 14)
assert_equal 3, @helper.previous(thursday).wday
end
it 'skips weekend by default' do
monday = Date.new(2016, 7, 18)
assert_equal 5, @helper.previous(monday).wday
end
it 'does not skip weekend if skip_weekend is set' do
monday = Date.new(2016, 7, 18)
assert_equal 0, @helper.previous(monday, false).wday
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/utils/slack_test.rb | test/lib/worque/utils/slack_test.rb | require 'test_helper'
require 'webmock/minitest'
require 'worque/utils/slack'
describe Worque::Utils::Slack do
describe '#post' do
before do
stubbed_result = {
"ok"=>true,
"channel"=>"secret",
"ts"=>"1469116417.000010",
"message" => {
"type"=>"message",
"user"=>"secret",
"text"=>"Hello World from the other side",
"bot_id"=>"secret",
"ts"=>"1469116417.000010"
}
}.to_json
stub_request(:post, "http://slack.com:443/api/chat.postMessage").
to_return(status: 200, body: stubbed_result, headers: {})
stub_request(:post, "https://slack.com/api/chat.postMessage").
to_return(status: 200, body: stubbed_result, headers: {})
end
it 'posts message to slack' do
token = 'just-a-token'
result = Worque::Utils::Slack
.new(token)
.post('#cam-test', "Hello World from Cam's computer")
assert result['ok']
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/test/lib/worque/utils/config_file_test.rb | test/lib/worque/utils/config_file_test.rb | require 'test_helper'
require 'worque/default_config'
describe Worque::DefaultConfig do
describe '#initialize' do
it 'takes config' do
config = Worque::DefaultConfig.new(path: '/foo', slack_token: 'bar')
assert_equal({path: '/foo', slack_token: 'bar'}, config.data)
end
end
describe '#load!' do
describe 'if ~/.worquerc exists' do
it 'loads from ~/.worquerc' do
worquerc = {'foo' => 'bar'}.to_json
File.stub(:read, worquerc) do
config = Worque::DefaultConfig.load!
assert_kind_of(Worque::Hash, config.data)
assert_equal({ 'foo' => 'bar' }, config.data)
end
end
end
describe 'if ~/.worquerc does not exist' do
it 'returns an empty hash' do
error_invocation = Proc.new { raise Errno::ENOENT }
File.stub(:read, error_invocation) do
config = Worque::DefaultConfig.load!
assert_equal({}, config.data)
end
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque.rb | lib/worque.rb | require "worque/version"
require 'worque/cli'
module Worque
InvalidPath = Class.new(StandardError)
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/version.rb | lib/worque/version.rb | module Worque
VERSION = "0.3.0"
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/default_config.rb | lib/worque/default_config.rb | module Worque
class Hash < ::Thor::CoreExt::HashWithIndifferentAccess; end
class DefaultConfig
attr_reader :data
def initialize(data = ::Worque::Hash.new)
@data = data
end
class << self
def load!
new(::Worque::Hash.new(parsed_config))
end
private
def parsed_config
JSON.parse(load_file)
rescue Errno::ENOENT
{}
end
def load_file
File.read(config_file_path)
end
def config_file_path
"#{Dir.home}/.worquerc"
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/cli.rb | lib/worque/cli.rb | require 'thor'
require 'worque/command/todo/action'
require 'worque/command/todo/options'
require 'worque/command/push/action'
require 'worque/command/push/options'
require 'worque/default_config'
module Worque
class CLI < ::Thor
package_name 'Worque CLI'
desc 'todo', 'Make a todo'
method_option :for, type: :string, enum: ['today', 'yesterday', 'tomorrow'], default: 'today'
method_option :skip_weekend, type: :boolean, default: true
method_option :path, type: :string
method_option :append_task, type: :string
method_option :template_path, type: :string
def todo
begin
default_opts = Worque::DefaultConfig.load!.data
result = Worque::Command::Todo::Action.run(default_opts.merge options)
rescue InvalidPath => e
$stderr.puts e.message
end
$stdout.puts result
end
desc 'push', 'Push your notes to Slack channel'
method_option :path, type: :string
method_option :for, type: :string, enum: ['today', 'yesterday', 'tomorrow'], default: 'today'
method_option :channel, required: true, type: :string, desc: 'Can be channel, private group ID or name. E.g. #daily-report'
def push
default_opts = Worque::DefaultConfig.load!.data
$stdout.puts Worque::Command::Push::Action.run(default_opts.merge options)
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/command/push/options.rb | lib/worque/command/push/options.rb | module Worque
module Command
class Push::Options
attr_reader :channel
attr_reader :token
attr_reader :for
attr_reader :path
def initialize(options)
@channel = options[:channel]
@path = options[:path]
@for = options[:for]
@token = options[:token]
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/command/push/action.rb | lib/worque/command/push/action.rb | require 'worque/utils/slack'
require 'worque/utils/business_day'
require 'json'
module Worque
module Command
module Push
class Action
REPORT_FILE_PATH_FORMAT = "%<worque_path>s/notes-%<date_for>s.md".freeze
def initialize(options)
@options = options
end
def call
slack = Worque::Utils::Slack.new(options.token)
JSON.dump(slack.post(options.channel, report_file_content))
end
class << self
def run(options)
require 'worque/command/push/options'
new(Worque::Command::Push::Options.new(options)).call()
end
end
private
attr_reader :options
def date_for
case options.for.to_sym
when :today
Date.today
when :yesterday
Worque::Utils::BusinessDay.previous(Date.today, true)
end
end
def report_file_content
File.open(report_file_path).read
end
def report_file_path
REPORT_FILE_PATH_FORMAT % Hash[
worque_path: options.path,
date_for: date_for
]
end
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/command/todo/options.rb | lib/worque/command/todo/options.rb | require 'optparse'
require 'pathname'
module Worque
module Command
class Todo::Options
attr_accessor :path
attr_accessor :for
attr_accessor :append_task
attr_writer :skip_weekend
attr_reader :template_path
def initialize(opts)
@path = opts[:path]
@skip_weekend = opts[:skip_weekend]
@for = opts[:for]
@append_task = opts[:append_task]
@template_path = opts.fetch(:template_path, nil)
end
def skip_weekend?
!!@skip_weekend
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/command/todo/action.rb | lib/worque/command/todo/action.rb | require 'worque/utils/command'
require 'worque/utils/business_day'
require 'date'
module Worque
module Command
module Todo
class Action
FILE_PATH_FORMAT = "%<path>s/notes-%<date>s.md".freeze
def initialize(options)
@options = options
validate_options!
end
def call
Worque::Utils::Command.mkdir(options.path)
notes_file_path = filename(date_for).tap do |f|
Worque::Utils::Command.touch f
end
if options.template_path && File.read(notes_file_path) == ""
template = File.read(File.expand_path(options.template_path))
Worque::Utils::Command.append_text(notes_file_path, template)
end
if options.append_task
Worque::Utils::Command.append_text(notes_file_path, options.append_task)
end
notes_file_path
end
class << self
def run(options)
new(Worque::Command::Todo::Options.new(options)).call()
end
end
private
attr_reader :options
def date_for
case options.for.to_sym
when :today
Date.today
when :yesterday
Worque::Utils::BusinessDay.previous(Date.today, options.skip_weekend?)
when :tomorrow
Worque::Utils::BusinessDay.next(Date.today, options.skip_weekend?)
end
end
def filename(date)
FILE_PATH_FORMAT % { path: options.path, date: date }
end
def validate_options!
if options.path.to_s.empty?
raise InvalidPath, 'Neither --path nor WORQUE_PATH is not set'
end
end
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/utils/command.rb | lib/worque/utils/command.rb | require 'fileutils'
module Worque
module Utils
module Command
extend self
def mkdir(dir)
FileUtils.mkdir_p(dir)
end
def touch(path)
FileUtils.touch(path)
end
def append_text(path, text)
File.open(path, 'a') do |f|
f.puts "#{text}\n"
end
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/utils/business_day.rb | lib/worque/utils/business_day.rb | module Worque
module Utils
module BusinessDay
extend self
def next(date, skip_weekend = true)
shift(date, 1, skip_weekend)
end
def previous(date, skip_weekend = true)
shift(date, -1, skip_weekend)
end
def previous_continuous(date)
shift(date, -1, false)
end
private
def shift(date, inc, skip_weekend = true)
return date + inc unless skip_weekend && weekend?(date + inc)
shift(date + inc, inc, skip_weekend)
end
def weekend?(date)
date.wday == 0 || date.wday == 6
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
qcam/worque | https://github.com/qcam/worque/blob/dc90cca76063d4233e26769d5edc0498c8203a0a/lib/worque/utils/slack.rb | lib/worque/utils/slack.rb | require 'json'
require 'net/http'
module Worque
module Utils
class Slack
def initialize(token)
@token = token
end
def post(channel, message)
JSON.parse(post_form(channel, message).body)
end
private
def post_form(channel, message)
uri = URI.parse('https://slack.com/api/chat.postMessage')
Net::HTTP.post_form(uri, as_user: true, channel: channel, token: @token, text: message)
end
end
end
end
| ruby | MIT | dc90cca76063d4233e26769d5edc0498c8203a0a | 2026-01-04T17:55:06.898707Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/chat_result_spec.rb | spec/chat_result_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::ChatResult, :unit do
describe '#initialize' do
context 'when initialized with choices and metrics' do
let ( :choice_attributes ) do
[
{
end_reason: :ended,
end_sequence: 'Goodbye.',
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'Hello, how can I assist you?' }
]
}
},
{
end_reason: :token_limit_exceeded,
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'This is too long to process.' }
]
}
}
]
end
let( :metrics_attributes ) do
{
duration: 1500,
input_tokens: 100,
output_tokens: 200
}
end
let( :chat_attributes ) do
{
choices: choice_attributes,
metrics: metrics_attributes
}
end
it 'sets the attributes correctly' do
chat_result = described_class.new( chat_attributes )
expect( chat_result.choices.length ).to eq( 2 )
expect( chat_result.choices.first ).to be_an_instance_of( Intelligence::ChatResultChoice )
# verify choices content
expected_message = Intelligence::Message.new( :assistant )
expected_message << Intelligence::MessageContent::Text.new( text: 'Hello, how can I assist you?' )
expect( chat_result.choices.first.message.to_h ).to eq( expected_message.to_h )
expect( chat_result.metrics ).to be_an_instance_of( Intelligence::ChatMetrics )
expect( chat_result.metrics.duration ).to eq( 1500 )
expect( chat_result.metrics.input_tokens ).to eq( 100 )
expect( chat_result.metrics.output_tokens ).to eq( 200 )
end
end
context 'when initialized without metrics' do
let( :choice_attributes ) do
[
{
end_reason: :ended,
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'Test message without metrics.' }
]
}
}
]
end
let( :chat_attributes ) do
{ choices: choice_attributes }
end
it 'sets choices and metrics correctly' do
chat_result = described_class.new( chat_attributes )
expect( chat_result.choices.length ).to eq( 1 )
expect( chat_result.choices.first ).to be_an_instance_of( Intelligence::ChatResultChoice )
expect( chat_result.metrics ).to be_nil
end
end
context 'when initialized without choices' do
let( :chat_attributes ) do
{
metrics: {
duration: 1200,
input_tokens: 80,
output_tokens: 160
}
}
end
it 'sets choices as an empty array' do
chat_result = described_class.new( chat_attributes )
expect( chat_result.choices ).to eq( [] )
expect( chat_result.metrics ).to be_an_instance_of( Intelligence::ChatMetrics )
end
end
context 'when initialized with empty attributes' do
it 'sets choices as empty array and metrics as nil' do
chat_result = described_class.new( {} )
expect( chat_result.choices ).to eq( [] )
expect( chat_result.metrics ).to be_nil
end
end
context 'when initialize includes arbitrary additional keys' do
let( :choice_attributes ) do
[
{
end_reason: :ended,
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'Payload test.' }
]
}
}
]
end
let( :chat_attributes ) do
{
id: 'abc-123',
user: 'alice',
temperature: 0.85,
model: 'gpt-4o-mini',
custom_flag: true,
choices: choice_attributes
# no metrics key
}
end
let( :chat_result ) { described_class.new( chat_attributes ) }
it 'exposes an extra key via []' do
expect( chat_result[ :temperature ] ).to eq( 0.85 )
end
it 'responds correctly to key?' do
expect( chat_result.key?( :model ) ).to be true
expect( chat_result.key?( :metrics ) ).to be false
end
it 'responds correctly to include?' do
expect( chat_result.include?( :custom_flag ) ).to be true
end
it 'enumerates extra attributes with each' do
expect( chat_result.each.to_h ).to include(
id: 'abc-123',
user: 'alice',
temperature: 0.85,
model: 'gpt-4o-mini',
custom_flag: true
)
end
it 'reports the correct size' do
expect( chat_result.size ).to eq( 5 )
end
it 'is not empty' do
expect( chat_result ).not_to be_empty
end
end
context 'when no extra keys are provided' do
let( :chat_result ) { described_class.new( choices: [] ) }
it 'returns nil for unknown keys with []' do
expect( chat_result[ :does_not_exist ] ).to be_nil
end
it 'returns false from key? and include?' do
expect( chat_result.key?( :does_not_exist ) ).to be false
expect( chat_result.include?( :does_not_exist ) ).to be false
end
it 'enumerates to an empty hash' do
expect( chat_result.each.to_h ).to eq( {} )
end
it 'reports size as zero' do
expect( chat_result.size ).to eq( 0 )
end
it 'is empty' do
expect( chat_result ).to be_empty
end
end
end
describe '#message' do
context 'when choices are present' do
let( :choice_attributes ) do
[
{
end_reason: :ended,
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'First choice message.' }
]
}
},
{
end_reason: :ended,
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'Second choice message.' }
]
}
}
]
end
let( :chat_attributes ) do
{ choices: choice_attributes }
end
it 'returns the message of the first choice' do
chat_result = described_class.new( chat_attributes )
message = chat_result.message
expected_message = Intelligence::Message.new( :assistant )
expected_message << Intelligence::MessageContent::Text.new( text: 'First choice message.' )
expect( message.to_h ).to eq( expected_message.to_h )
end
end
context 'when choices are empty' do
it 'returns nil' do
chat_result = described_class.new( choices: [] )
expect( chat_result.message ).to be_nil
end
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/adapter_error_spec.rb | spec/adapter_error_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::AdapterError, :unit do
describe '#initialize' do
it 'sets the error message correctly based on adapter_type and text' do
error = described_class.new( :some_adapter, 'failed to initialize' )
expect( error.message ).to eq( 'The SomeAdapter adapter failed to initialize.' )
end
it 'formats adapter_type with underscores into camel case' do
error = described_class.new( :some_adapter_type, 'encountered an error' )
expect( error.message ).to eq( 'The SomeAdapterType adapter encountered an error.' )
end
it 'handles adapter_type as a string' do
error = described_class.new( 'another_adapter', 'is not available' )
expect( error.message ).to eq( 'The AnotherAdapter adapter is not available.' )
end
it 'handles text with complex sentences' do
error = described_class.new( :complex_adapter, 'could not process the request due to unexpected input' )
expect( error.message ).to eq( 'The ComplexAdapter adapter could not process the request due to unexpected input.' )
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/message_spec.rb | spec/message_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::Message, :unit do
let( :text_content ) {
Intelligence::MessageContent.build!( :text, text: 'text' )
}
let( :binary_content ) {
Intelligence::MessageContent.build!( :binary, content_type: 'image/jpg', bytes: '...bytes...' )
}
describe '.build' do
context 'when given no block and no attributes' do
it 'raises an ArgumentError' do
expect { described_class.build! }.to(
raise_error(
DynamicSchema::RequiredOptionError,
/The attribute 'role' is required/
)
)
end
end
context 'when given no block and attributes that contain a role' do
it 'initializes with a role as a symbol' do
message = described_class.build!( role: :system )
expect( message.role ).to eq( :system )
end
end
context 'when given a role and multiple content items of different types' do
it 'initializes with a role and mutliple content items' do
message = described_class.build! do
role :user
content text: 'text 0'
content do
type :binary
content_type 'image/png'
bytes '..bytes..'
end
end
expect( message.role ).to eq( :user )
expect( message.contents.size ).to eq( 2 )
expect( message.contents[ 0 ] ).to be_a( Intelligence::MessageContent::Text )
expect( message.contents[ 1 ] ).to be_a( Intelligence::MessageContent::Binary )
end
end
end
describe '#initialize' do
context 'when given a valid role' do
it 'sets the role as a symbol' do
message = described_class.new( :user )
expect( message.role ).to eq( :user )
end
it 'initializes contents as an empty array when no content is provided' do
message = described_class.new( 'system' )
expect( message.contents ).to eq( [] )
end
end
context 'when given an invalid role' do
it 'raises an ArgumentError' do
expect { described_class.new( :invalid_role ) }.to(
raise_error( ArgumentError, /The role is invalid/ )
)
end
end
end
describe '#text' do
context 'when a message is initialized with a role and no content' do
it 'returns an empty string' do
message = described_class.new( :assistant )
expect( message.text ).to eq( '' )
end
end
context 'when a message is initialized with a role and text content' do
it 'returns the text of that text content' do
message = described_class.new( :user )
message.append_content( text_content )
expect( message.text ).to eq( 'text' )
end
end
context 'when a message is initialized with a role and binary content' do
it 'returns an empty string' do
message = described_class.new( :user )
message.append_content( binary_content )
expect( message.text ).to eq( '' )
end
end
context 'when a message is initialized with a role and multiple instances of text content' do
it 'returns the text with the text content joined by a newline' do
message = described_class.new( :user )
message.append_content( text_content )
message.append_content( text_content )
expect( message.text ).to eq( "text\ntext" )
end
end
context 'when a message is initialized with a role and text, binary, text content interleaved' do
it 'returns the text with the text content joined by a newline' do
message = described_class.new( :user )
message.append_content( text_content )
message.append_content( binary_content )
message.append_content( text_content )
expect( message.text ).to eq( "text\ntext" )
end
end
end
describe '#append_content' do
it 'adds the content to the contents array' do
message = described_class.new( :user )
content = double( 'content' )
message.append_content( content )
expect( message.contents ).to include( content )
end
it 'does not add nil content' do
message = described_class.new( :user )
message.append_content( nil )
expect( message.contents ).to be_empty
end
it 'returns self' do
message = described_class.new( :user )
content = double( 'content' )
expect( message.append_content( content ) ).to eq( message )
end
end
describe '#each_content' do
it 'iterates over each content in contents' do
message = described_class.new( :user )
content1 = double( 'content1' )
content2 = double( 'content2' )
message.append_content( content1 )
message.append_content( content2 )
contents = []
message.each_content { | content | contents << content }
expect( contents ).to eq( [ content1, content2 ] )
end
end
describe '#empty?' do
it 'returns true when contents are empty' do
message = described_class.new( :user )
expect( message.empty? ).to be true
end
it 'returns false when contents are not empty' do
message = described_class.new( :user )
content = double( 'content' )
message.append_content( content )
expect( message.empty? ).to be false
end
end
describe '#valid?' do
it 'returns true when role is set and all contents are valid' do
valid_content = double( 'content', valid?: true )
message = described_class.new( :user )
message.append_content( valid_content )
expect( message.valid? ).to be true
end
it 'returns false when role is nil' do
message = described_class.allocate
message.instance_variable_set( :@role, nil )
message.instance_variable_set( :@contents, [] )
expect( message.valid? ).to be false
end
it 'returns false when any content is invalid' do
valid_content = double( 'content', valid?: true )
invalid_content = double( 'content', valid?: false )
message = described_class.new( :user )
message.append_content( valid_content )
message.append_content( invalid_content )
expect( message.valid? ).to be false
end
end
describe '#to_h' do
it 'returns a hash representation with role and contents' do
content1 = double( 'content1', to_h: { type: :text, text: 'Hello' } )
content2 = double( 'content2', to_h: { type: :image, url: 'http://example.com/image.png' } )
message = described_class.new( :assistant )
message.append_content( content1 )
message.append_content( content2 )
expected_hash = {
role: :assistant,
contents: [
{ type: :text, text: 'Hello' },
{ type: :image, url: 'http://example.com/image.png' }
]
}
expect( message.to_h ).to eq( expected_hash )
end
end
describe '#<<' do
it 'aliases append_content method' do
message = described_class.new( :user )
content = double( 'content' )
message << content
expect( message.contents ).to include( content )
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/conversation_spec.rb | spec/conversation_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::Conversation, :unit do
describe '.build' do
context 'when given no attributes or configuration' do
it 'creates an empty conversation' do
conversation = described_class.build
expect( conversation.has_system_message? ).to be false
expect( conversation.has_messages? ).to be false
end
end
context 'when given a system message in the configuration' do
it 'creates a conversation with a system message' do
conversation = described_class.build do
system_message do
content do
text 'system message'
end
end
end
expect( conversation.has_system_message? ).to be true
expect( conversation.system_message.role ).to eq :system
expect( conversation.system_message.text ).to eq 'system message'
end
end
end
describe '#initialize' do
context 'when given attributes with system_message and messages' do
it 'initializes system_message and messages correctly' do
system_message = Intelligence::Message.new( :system )
messages = [
Intelligence::Message.new( :user ),
Intelligence::Message.new( :assistant )
]
conversation = described_class.new()
conversation.system_message = system_message
conversation << messages
expect( conversation.system_message.to_h ).to eq( system_message.to_h )
expect( conversation.messages ).to eq( messages )
expect( conversation.messages ).not_to be( messages )
end
end
context 'when given empty attributes' do
it 'initializes with default values' do
conversation = described_class.new
expect( conversation.system_message ).to be_nil
expect( conversation.messages ).to eq( [] )
end
end
end
describe '#has_system_message?' do
context 'when system_message is present and not empty' do
it 'returns true' do
content = Intelligence::MessageContent::Text.new( text: 'System message content' )
system_message = Intelligence::Message.new( :system )
system_message.append_content( content )
conversation = described_class.new
conversation.system_message = system_message
expect( conversation.has_system_message? ).to be true
end
end
context 'when system_message is nil' do
it 'returns false' do
conversation = described_class.new
expect( conversation.has_system_message? ).to be false
end
end
context 'when system_message is empty' do
it 'returns false' do
system_message = Intelligence::Message.new( :system )
conversation = described_class.new
conversation.system_message = system_message
expect( conversation.has_system_message? ).to be false
end
end
end
describe '#has_messages?' do
context 'when messages are present' do
it 'returns true' do
message = Intelligence::Message.new( :user )
conversation = described_class.new
conversation.messages << message
expect( conversation.has_messages? ).to be true
end
end
context 'when messages are empty' do
it 'returns false' do
conversation = described_class.new
expect( conversation.has_messages? ).to be false
end
end
end
describe '#system_message=' do
context 'when message is a valid Intelligence::Message with role :system' do
it 'sets the system_message' do
message = Intelligence::Message.new( :system )
conversation = described_class.new
conversation.system_message = message
expect( conversation.system_message ).to eq( message )
end
end
context 'when message is not an Intelligence::Message' do
it 'raises ArgumentError' do
message = 'Not a message object' # Invalid message
conversation = described_class.new
expect {
conversation.system_message = message
}.to raise_error( ArgumentError, /The system message must be a Intelligence::Message./ )
end
end
context "when message's role is not :system" do
it 'raises ArgumentError' do
message = Intelligence::Message.new( :user )
conversation = described_class.new
expect {
conversation.system_message = message
}.to raise_error( ArgumentError, /The system message MUST have a role of 'system'./ )
end
end
end
describe '#to_h' do
it 'returns a hash representation of the conversation' do
system_message = Intelligence::Message.new( :system )
message1 = Intelligence::Message.new( :user )
message2 = Intelligence::Message.new( :assistant )
conversation = described_class.new
conversation.system_message = system_message
conversation.messages << message1 << message2
expected_hash = {
system_message: system_message.to_h,
messages: [ message1.to_h, message2.to_h ],
}
expect( conversation.to_h ).to eq( expected_hash )
end
it 'handles nil system_message' do
conversation = described_class.new
expect( conversation.to_h ).to eq( { messages: [] } )
end
it 'handles empty messages' do
system_message = Intelligence::Message.new( :system )
conversation = described_class.new
conversation.system_message = system_message
expected_hash = {
system_message: system_message.to_h,
messages: [],
}
expect( conversation.to_h ).to eq( expected_hash )
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/chat_result_choice_spec.rb | spec/chat_result_choice_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::ChatResultChoice, :unit do
describe '#initialize' do
context 'when initialized with message, end_reason, and end_sequence' do
let( :chat_choice_attributes ) do
{
end_reason: :ended,
end_sequence: 'Goodbye.',
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'Hello, how can I assist you?' }
]
}
}
end
let( :chat_result_choice ) { described_class.new( chat_choice_attributes ) }
it 'sets the attributes correctly' do
expect( chat_result_choice.end_reason ).to eq( :ended )
expect( chat_result_choice.end_sequence ).to eq( 'Goodbye.' )
expected_message = Intelligence::Message.new( :assistant )
expected_message << Intelligence::MessageContent::Text.new( text: 'Hello, how can I assist you?' )
expect( chat_result_choice.message.to_h ).to eq( expected_message.to_h )
end
end
context 'when initialized without message' do
let( :chat_choice_attributes ) do
{
end_reason: :filtered,
end_sequence: 'Inappropriate content'
# no :message key
}
end
let( :chat_result_choice ) { described_class.new( chat_choice_attributes ) }
it 'sets message to nil' do
expect( chat_result_choice.message ).to be_nil
expect( chat_result_choice.end_reason ).to eq( :filtered )
expect( chat_result_choice.end_sequence ).to eq( 'Inappropriate content' )
end
end
end
describe 'message building' do
context 'when role is absent' do
let( :chat_choice_attributes ) do
{
message: {
contents: [
{ type: :text, text: 'Default role message' }
]
}
}
end
let( :chat_result_choice ) { described_class.new( chat_choice_attributes ) }
it 'defaults role to :assistant' do
expected_message = Intelligence::Message.new( :assistant )
expected_message << Intelligence::MessageContent::Text.new( text: 'Default role message' )
expect( chat_result_choice.message.to_h ).to eq( expected_message.to_h )
end
end
context 'when role is provided' do
let( :chat_choice_attributes ) do
{
message: {
role: 'user',
contents: [
{ type: :text, text: 'I need help with my account.' }
]
}
}
end
let( :chat_result_choice ) { described_class.new( chat_choice_attributes ) }
it 'uses the provided role' do
expected_message = Intelligence::Message.new( :user )
expected_message << Intelligence::MessageContent::Text.new( text: 'I need help with my account.' )
expect( chat_result_choice.message.to_h ).to eq( expected_message.to_h )
end
end
context 'when multiple contents are present' do
let( :chat_choice_attributes ) do
{
message: {
role: 'assistant',
contents: [
{ type: :text, text: 'First line of response.' },
{ type: :text, text: 'Second line of response.' }
]
}
}
end
let( :chat_result_choice ) { described_class.new( chat_choice_attributes ) }
it 'adds all contents to the message' do
expected_message = Intelligence::Message.new( :assistant )
expected_message << Intelligence::MessageContent::Text.new( text: 'First line of response.' )
expected_message << Intelligence::MessageContent::Text.new( text: 'Second line of response.' )
expect( chat_result_choice.message.to_h ).to eq( expected_message.to_h )
end
end
end
describe 'additional attribute payload' do
context 'when extra keys are present' do
let( :chat_choice_attributes ) do
{
confidence: 0.92,
source: 'model-a'
}
end
let( :chat_result_choice ) { described_class.new( chat_choice_attributes ) }
it 'exposes values with []' do
expect( chat_result_choice[ :confidence ] ).to eq( 0.92 )
end
it 'responds to key? and include?' do
expect( chat_result_choice.key?( :source ) ).to be true
expect( chat_result_choice.include?( :source ) ).to be true
expect( chat_result_choice.key?( :missing ) ).to be false
end
it 'enumerates attributes with each' do
expect( chat_result_choice.each.to_h ).to include(
confidence: 0.92,
source: 'model-a'
)
end
it 'reports correct size and empty? status' do
expect( chat_result_choice.size ).to eq( 2 )
expect( chat_result_choice ).not_to be_empty
end
end
context 'when no extra keys are present' do
let( :chat_result_choice ) { described_class.new( {} ) }
it 'behaves like an empty hash' do
expect( chat_result_choice.empty? ).to be true
expect( chat_result_choice.size ).to eq( 0 )
expect( chat_result_choice[ :anything ] ).to be_nil
expect( chat_result_choice.each.to_h ).to eq( {} )
end
end
end
end | ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/chat_metrics_spec.rb | spec/chat_metrics_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::ChatMetrics, :unit do
describe '#initialize' do
context 'when initialized with all attributes' do
it 'sets the attributes correctly' do
attributes = {
duration: 1500,
input_tokens: 100,
output_tokens: 200
}
chat_metrics = described_class.new( attributes )
expect( chat_metrics.duration ).to eq( 1500 )
expect( chat_metrics.input_tokens ).to eq( 100 )
expect( chat_metrics.output_tokens ).to eq( 200 )
end
end
context 'when initialized with some attributes missing' do
it 'sets only the provided attributes' do
attributes = {
duration: 1500,
input_tokens: 100
# output_tokens is missing
}
chat_metrics = described_class.new( attributes )
expect( chat_metrics.duration ).to eq( 1500 )
expect( chat_metrics.input_tokens ).to eq( 100 )
expect( chat_metrics.output_tokens ).to be_nil
end
end
context 'when initialized with empty attributes' do
it 'does not set any attributes' do
chat_metrics = described_class.new( {} )
expect( chat_metrics.duration ).to be_nil
expect( chat_metrics.input_tokens ).to be_nil
expect( chat_metrics.output_tokens ).to be_nil
end
end
context 'when initialized with attributes that do not correspond to instance variables' do
it 'ignores unknown attributes' do
attributes = {
duration: 1500,
input_tokens: 100,
output_tokens: 200,
unknown_attribute: 'ignored'
}
chat_metrics = described_class.new( attributes )
expect( chat_metrics.duration ).to eq( 1500 )
expect( chat_metrics.input_tokens ).to eq( 100 )
expect( chat_metrics.output_tokens ).to eq( 200 )
expect( chat_metrics.instance_variable_defined?( :@unknown_attribute ) ).to be false
end
end
end
describe '#total_tokens' do
context 'when input_tokens and output_tokens are set' do
it 'returns the sum of input_tokens and output_tokens' do
chat_metrics = described_class.new(
input_tokens: 100,
output_tokens: 200
)
expect( chat_metrics.total_tokens ).to eq( 300 )
end
it 'memoizes the total_tokens value' do
chat_metrics = described_class.new(
input_tokens: 100,
output_tokens: 200
)
# first call to total_tokens computes and sets @total_tokens
expect( chat_metrics.total_tokens ).to eq( 300 )
# change input_tokens and output_tokens
chat_metrics.instance_variable_set( :@input_tokens, 150 )
chat_metrics.instance_variable_set( :@output_tokens, 250 )
# since @total_tokens is memoized, it should not change
expect( chat_metrics.total_tokens ).to eq( 300 )
end
end
context 'when input_tokens or output_tokens is nil' do
it 'returns nil if input_tokens is nil' do
chat_metrics = described_class.new(
input_tokens: nil,
output_tokens: 200
)
expect( chat_metrics.total_tokens ).to be_nil
end
it 'returns nil if output_tokens is nil' do
chat_metrics = described_class.new(
input_tokens: 100,
output_tokens: nil
)
expect( chat_metrics.total_tokens ).to be_nil
end
it 'returns nil if both input_tokens and output_tokens are nil' do
chat_metrics = described_class.new(
input_tokens: nil,
output_tokens: nil
)
expect( chat_metrics.total_tokens ).to be_nil
end
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/adapter_configuration_spec.rb | spec/adapter_configuration_spec.rb | require 'spec_helper'
module Intelligence
module ConfigurationTest
class Adapter < Intelligence::Adapter::Base
schema do
api_key String, required: true
settings default: {} do
timeout Integer
debug [ TrueClass, FalseClass ], default: false
logging do
level String, default: 'info'
end
end
end
attr_reader :api_key, :settings
def initialize( attributes = nil, configuration: nil )
super( attributes, configuration: configuration )
@api_key = self.options[ :api_key ]
@settings = self.options[ :settings ]
end
end
end
end
RSpec.describe Intelligence::ConfigurationTest::Adapter, :unit do
describe '.schema' do
it 'allows setting and retrieving schema parameters' do
adapter = described_class.build( api_key: 'test_key' ) do
settings do
timeout 30
debug true
end
end
expect( adapter.api_key ).to eq( 'test_key' )
expect( adapter.settings.to_h ).to eq( { timeout: 30, debug: true } )
end
it 'uses default values when parameters are not provided' do
adapter = described_class.build( api_key: 'test_key' )
expect( adapter.api_key ).to eq( 'test_key' )
expect( adapter.settings ).to eq( { debug: false } )
end
it 'overrides attribute values with block values' do
adapter = described_class.build( api_key: 'initial_key', options: { timeout: 20 } ) do
api_key 'overridden_key'
settings do
timeout 40
end
end
expect( adapter.api_key ).to eq( 'overridden_key' )
expect( adapter.settings ).to eq( { timeout: 40, debug: false } )
end
it 'handles nested parameters parameters' do
adapter = described_class.build( api_key: 'test_key' ) do
settings do
logging do
level 'debug'
end
end
end
expect( adapter.settings.to_h ).to eq( { debug: false, logging: { level: 'debug' } } )
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/error_result_spec.rb | spec/error_result_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::ErrorResult, :unit do
describe '#initialize' do
context 'when initialized with all attributes' do
it 'sets the attributes correctly' do
error_attributes = {
error_type: :invalid_request_error,
error: 'Invalid request format',
error_description: 'There was an issue with the format or content of your request.'
}
error_result = described_class.new( error_attributes )
expect( error_result.error_type ).to eq( :invalid_request_error )
expect( error_result.error ).to eq( 'Invalid request format' )
expect( error_result.error_description ).to eq( 'There was an issue with the format or content of your request.' )
end
end
context 'when initialized with some attributes missing' do
it 'sets only the provided attributes' do
error_attributes = {
error_type: :authentication_error,
error_description: "There's an issue with your API key."
# error is missing
}
error_result = described_class.new( error_attributes )
expect( error_result.error_type ).to eq( :authentication_error )
expect( error_result.error ).to be_nil
expect( error_result.error_description ).to eq( "There's an issue with your API key." )
end
end
context 'when initialized with unknown attributes' do
it 'ignores unknown attributes' do
error_attributes = {
error_type: :unknown_error,
error: 'An unexpected error occurred',
error_description: 'An unknown error occurred.',
unknown_attribute: 'should be ignored'
}
error_result = described_class.new( error_attributes )
expect( error_result.error_type ).to eq( :unknown_error )
expect( error_result.error ).to eq( 'An unexpected error occurred' )
expect( error_result.error_description ).to eq( 'An unknown error occurred.' )
expect( error_result.instance_variable_defined?( :@unknown_attribute ) ).to be false
end
end
context 'when initialized with empty attributes' do
it 'sets all attributes to nil' do
error_result = described_class.new( {} )
expect( error_result.error_type ).to be_nil
expect( error_result.error ).to be_nil
expect( error_result.error_description ).to be_nil
end
end
end
describe '#empty?' do
context 'when all attributes are nil' do
it 'returns true' do
error_result = described_class.new( {} )
expect( error_result.empty? ).to be true
end
end
context 'when any attribute is set' do
it 'returns false if error_type is set' do
error_result = described_class.new( error_type: :api_error )
expect( error_result.empty? ).to be false
end
it 'returns false if error is set' do
error_result = described_class.new( error: 'Some error message' )
expect( error_result.empty? ).to be false
end
it 'returns false if error_description is set' do
error_result = described_class.new( error_description: 'An error occurred' )
expect( error_result.empty? ).to be false
end
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/adapter_spec.rb | spec/adapter_spec.rb | require 'spec_helper'
# define a minimal adapter class for testing purposes
module Intelligence
module TestAdapter
class Adapter < Intelligence::Adapter::Base
schema do
key
end
end
end
end
RSpec.describe Intelligence::Adapter, :unit do
describe '.[]' do
context 'when adapter_type is nil' do
it 'raises an ArgumentError' do
expect {
described_class[ nil ]
}.to raise_error( ArgumentError, 'An adapter type is required but nil was given.' )
end
end
context 'when adapter class exists' do
it 'returns the adapter class' do
adapter_class = described_class[ :test_adapter ]
expect( adapter_class ).to eq( Intelligence::TestAdapter::Adapter )
end
end
context 'when adapter class does not exist initially but found after require' do
before do
Intelligence.send( :remove_const, :TestRequireAdapter ) if Intelligence.const_defined?( :TestRequireAdapter )
allow( described_class ).to receive( :require ).and_return( true )
allow( Intelligence ).to receive( :const_get ).with( 'TestRequireAdapter::Adapter' ).and_wrap_original do | original_method, *args |
if Intelligence.const_defined?( :TestRequireAdapter )
original_method.call( *args )
else
module Intelligence
module TestRequireAdapter
class Adapter < Intelligence::Adapter::Base
end
end
end
original_method.call( *args )
end
end
end
it 'requires the adapter file and returns the adapter class' do
adapter_class = described_class[ :test_require_adapter ]
expect( adapter_class ).to eq( Intelligence::TestRequireAdapter::Adapter )
end
end
context 'when adapter class does not exist and cannot be required' do
before do
allow( described_class ).to receive( :require ).and_return( false )
end
it 'raises an ArgumentError' do
expect {
described_class[ :nonexistent_adapter ]
}.to raise_error( ArgumentError, /The Intelligence adapter file .* is missing or does not define NonexistentAdapter::Adapter./ )
end
end
context 'when adapter class cannot be found after require' do
before do
allow( described_class ).to receive( :require ).and_return( true )
allow( Intelligence ).to receive( :const_get ).and_return( nil )
end
it 'raises an ArgumentError' do
expect {
described_class[ :unknown_adapter ]
}.to raise_error( ArgumentError, 'An unknown Intelligence adapter unknown_adapter was requested.' )
end
end
end
describe '.build!' do
it 'builds an instance of the adapter class with given type and attributes' do
attributes = { key: 'value' }
adapter_instance = described_class.build!( :test_adapter, attributes )
expect( adapter_instance ).to be_an_instance_of( Intelligence::TestAdapter::Adapter )
expect( adapter_instance.instance_variable_get( :@options ) ).to eq( attributes )
end
it 'passes a block to the adapter initializer' do
attributes = { key: 'value' }
instance_variable_set_in_block = nil
adapter_instance = described_class.build!( :test_adapter, attributes ) do
instance_variable_set_in_block = true
end
expect( instance_variable_set_in_block ).to be true
expect( adapter_instance ).to be_an_instance_of( Intelligence::TestAdapter::Adapter )
expect( adapter_instance.instance_variable_get( :@options ) ).to eq( attributes )
expect( instance_variable_set_in_block ).to be true
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/message_content_spec.rb | spec/message_content_spec.rb | require 'spec_helper'
RSpec.describe Intelligence::MessageContent, :unit do
describe '.build' do
context 'when the class for the provided type exists' do
it 'creates an instance of the correct class' do
# define a mock class for the test
class Intelligence::MessageContent::TestType < Intelligence::MessageContent::Base;
schema do
some_attribute
end
attr_reader :some_attribute
end
instance = Intelligence::MessageContent.build!( :test_type, some_attribute: 'value' )
expect( instance ).to be_a( Intelligence::MessageContent::TestType )
expect( instance.instance_variable_get( '@some_attribute' ) ).to eq( 'value' )
end
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/spec_helper.rb | spec/spec_helper.rb | require 'rspec'
require 'vcr'
require 'debug'
require 'intelligence'
Dir[ File.join( __dir__, 'support', '**', '*.rb' ) ].each { |f| require f }
RSpec.configure do | config |
config.formatter = :documentation
# allows using "describe" instead of "RSpec.describe"
config.expose_dsl_globally = true
config.expect_with :rspec do | expectations |
expectations.syntax = :expect
end
config.mock_with :rspec do | mocks |
mocks.syntax = :expect
end
ignore_cassettes = ( config.inclusion_filter.delete( :'ignore-cassettes' ) ? true : false )
record_cassettes = ( config.inclusion_filter.delete( :'record-cassettes' ) ? true : false )
config.define_derived_metadata do | metadata |
metadata[ :ignore_cassettes ] = true if ignore_cassettes
metadata[ :record_cassettes ] = true if record_cassettes
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/support/vcr_helper.rb | spec/support/vcr_helper.rb | require 'vcr'
SENSITIVE_URL_PARAMETERS = %w(
key
)
SENSITIVE_REQUEST_HEADERS = %w(
x-api-key api-key
)
SENSITIVE_RESPONSE_HEADERS = %w(
set-cookie Set-Cookie cf-ray request-id x-request-id x-cloud-trace-context
openai-organization
)
VCR.configure do | config |
config.cassette_library_dir = File.join( __dir__, '..', 'fixtures', 'cassettes' )
config.allow_http_connections_when_no_cassette = true
# general
config.filter_sensitive_data( '<TOKEN>') do | interaction |
authorization = interaction.request.headers[ 'Authorization' ]&.first
if authorization && match = authorization.match( /^Bearer\s+([^,\s]+)/ )
match.captures.first
end
end
config.before_record do | interaction |
SENSITIVE_URL_PARAMETERS.each do | key |
interaction.request.uri.gsub!( /(#{key}=)[^&]+/, "\\1<#{key.upcase}>" )
end
SENSITIVE_REQUEST_HEADERS.each do | header |
interaction.request.headers[ header ]&.map! { "<#{header.upcase}>" }
end
SENSITIVE_RESPONSE_HEADERS.each do | header |
interaction.response.headers[ header ]&.map! { "<#{header.upcase}>" }
end
end
end
CASSETTE_OPTIONS = {
serialize_with: :json,
match_requests_on: [
:method,
VCR.request_matchers.uri_without_params( *SENSITIVE_URL_PARAMETERS )
]
}
RSpec.shared_context 'vcr' do
around( :each ) do | example |
if example.metadata[ :ignore_cassettes ]
example.run
else
options = CASSETTE_OPTIONS.dup
options[ :record ] = :all if example.metadata[ :record_cassettes ]
VCR.use_cassette( example.metadata[ :full_description ], options ) do
example.run
end
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/support/fixture_helper.rb | spec/support/fixture_helper.rb | module FixtureHelperMethods
def fixture_file_path( file_name )
File.expand_path( File.join( '..', 'fixtures', 'files', file_name ), __dir__ )
end
end
RSpec.configure do | config |
config.include FixtureHelperMethods
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/support/intelligence_helper.rb | spec/support/intelligence_helper.rb | module IntelligenceHelper
def adapter_key( env_key )
raise "An #{env_key} must be defined in the environment." unless ENV[ env_key ]
ENV[ env_key ]
end
def adapter_connection
Faraday.new do | builder |
builder.adapter Faraday.default_adapter
builder.options.timeout = 240 # read timeout (default is 60)
builder.options.open_timeout = 30 # connection timeout (default is 60)
builder.use VCR::Middleware::Faraday
end
end
def create_conversation_without_system_message( *texts )
Intelligence::Conversation.build do
texts.each_with_index do | _text, index |
message do
role index.even? ? :user : :assistant
content do
text _text
end
end
end
end
end
def create_conversation( *texts )
Intelligence::Conversation.build do
system_message do
content do
text %Q(
You are integrated into a test platform. It is very important that you answer
succinctly and always provide the text in the requested format without any additional
text.
)
end
end
texts.each_with_index do | _text, index |
message do
role index.even? ? :user : :assistant
content do
text _text
end
end
end
end
end
def build_text_message( _role, _text )
Intelligence::Message.build! do
role _role
content do
text _text
end
end
end
def build_text_content( text )
Intelligence::MessageContent::Text.build!( text: text )
end
def build_binary_content( filepath )
content_type = MIME::Types.type_for( filepath ).first.to_s
bytes = File.binread( filepath )
Intelligence::MessageContent::Binary.build!( content_type: content_type, bytes: bytes )
end
def create_and_make_chat_request( adapter, conversation, options = nil )
request = Intelligence::ChatRequest.new( connection: adapter_connection, adapter: adapter )
request.chat( conversation, options )
end
def create_and_make_stream_request( adapter, conversation, options = nil, &block )
request = Intelligence::ChatRequest.new( connection: adapter_connection, adapter: adapter )
request.stream( conversation, options ) do | request |
request.receive_result do | result |
block.call( result ) if block_given?
end
end
end
def message_contents_to_text( message )
text = ''
message.contents.each do | content |
text += ( content.text || '' ) if content.is_a?( Intelligence::MessageContent::Text )
end
text
end
def response_error_description( response )
( response&.result&.respond_to?( :error_description ) ? response.result.error_description : nil ) || ''
end
end
RSpec.configure do | config |
config.include IntelligenceHelper
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
EndlessInternational/intelligence | https://github.com/EndlessInternational/intelligence/blob/2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a/spec/support/adapters/chat_requests_with_stop_sequence.rb | spec/support/adapters/chat_requests_with_stop_sequence.rb | require 'spec_helper'
RSpec.shared_examples 'chat requests with stop sequence' do | options = {} |
context 'where there is a single message that ends at stop sequence' do
it 'responds with generated text up to the stop sequence' do
response = create_and_make_chat_request(
send( options[ :adapter ] || :adapter ),
create_conversation( "count to ten in words, all lower case, one word per line\n" )
)
expect( response.success? ).to be( true ), response_error_description( response )
expect( response.result ).to be_a( Intelligence::ChatResult )
expect( response.result.choices ).not_to be_nil
expect( response.result.choices.length ).to eq( 1 )
expect( response.result.choices.first ).to be_a( Intelligence::ChatResultChoice )
choice = response.result.choices.first
expect( choice.end_reason ).to eq( options[ :end_reason ] || :ended )
expect( choice.message ).to be_a( Intelligence::Message )
expect( choice.message.contents ).not_to be_nil
expect( choice.message.contents.length ).to eq( 1 )
text = message_contents_to_text( choice.message )
expect( text ).to match( /four/i )
expect( text ).to_not match( /five/i )
end
end
context 'where there are multiple messages and the last ends at stop sequence' do
it 'responds with generated text up to the stop sequence' do
response = create_and_make_chat_request(
send( options[ :adapter ] || :adapter ),
create_conversation(
"count to five in words, one word per line\n",
"one\ntwo\nthree\nfour\nfive\n",
"count to ten in words, one word per line\n"
)
)
expect( response.success? ).to be( true ), response_error_description( response )
expect( response.result ).to be_a( Intelligence::ChatResult )
expect( response.result.choices ).not_to be_nil
expect( response.result.choices.length ).to eq( 1 )
expect( response.result.choices.first ).to be_a( Intelligence::ChatResultChoice )
choice = response.result.choices.first
expect( choice.end_reason ).to eq( options[ :end_reason ] || :ended )
expect( choice.message ).to be_a( Intelligence::Message )
expect( choice.message.contents ).not_to be_nil
expect( choice.message.contents.length ).to eq( 1 )
text = message_contents_to_text( choice.message )
expect( text ).to match( /four/i )
expect( text ).to_not match( /five/i )
end
end
end
| ruby | MIT | 2ea7d4c0121a2c3eb962bb6199df67d8a38cb50a | 2026-01-04T17:53:00.421273Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.