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 |
|---|---|---|---|---|---|---|---|---|
toddmazierski/mint-exporter | https://github.com/toddmazierski/mint-exporter/blob/443976130010255d3259817affb2e38b320aa0bf/lib/mint/config.rb | lib/mint/config.rb | module Mint
class Config
attr_accessor :username,
:password
end
end
| ruby | MIT | 443976130010255d3259817affb2e38b320aa0bf | 2026-01-04T17:52:31.479208Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/test/test_joint.rb | test/test_joint.rb | require 'helper'
class JointTest < Test::Unit::TestCase
include JointTestHelpers
def setup
super
@file = open_file('unixref.pdf')
@image = open_file('mr_t.jpg')
@image2 = open_file('harmony.png')
@test1 = open_file('test1.txt')
@test2 = open_file('test2.txt')
end
def teardown
all_files.each { |file| file.close }
end
context "Using Joint plugin" do
should "add each attachment to attachment_names" do
Asset.attachment_names.should == Set.new([:image, :file])
EmbeddedAsset.attachment_names.should == Set.new([:image, :file])
end
should "add keys for each attachment" do
key_names.each do |key|
Asset.keys.should include("image_#{key}")
Asset.keys.should include("file_#{key}")
EmbeddedAsset.keys.should include("image_#{key}")
EmbeddedAsset.keys.should include("file_#{key}")
end
end
should "add memoized accessors module" do
Asset.attachment_accessor_module.should be_instance_of(Module)
EmbeddedAsset.attachment_accessor_module.should be_instance_of(Module)
end
context "with inheritance" do
should "add attachment to attachment_names" do
BaseModel.attachment_names.should == Set.new([:file])
end
should "inherit attachments from superclass, but not share other inherited class attachments" do
Image.attachment_names.should == Set.new([:file, :image])
Video.attachment_names.should == Set.new([:file, :video])
end
should "add inherit keys from superclass" do
key_names.each do |key|
BaseModel.keys.should include("file_#{key}")
Image.keys.should include("file_#{key}")
Image.keys.should include("image_#{key}")
Video.keys.should include("file_#{key}")
Video.keys.should include("video_#{key}")
end
end
end
end
context "Assigning new attachments to document" do
setup do
@doc = Asset.create(:image => @image, :file => @file)
rewind_files
end
subject { @doc }
should "assign GridFS content_type" do
grid.get(subject.image_id).content_type.should == 'image/jpeg'
grid.get(subject.file_id).content_type.should == 'application/pdf'
end
should "assign joint keys" do
subject.image_size.should == 13661
subject.file_size.should == 68926
subject.image_type.should == "image/jpeg"
subject.file_type.should == "application/pdf"
subject.image_id.should_not be_nil
subject.file_id.should_not be_nil
subject.image_id.should be_instance_of(BSON::ObjectId)
subject.file_id.should be_instance_of(BSON::ObjectId)
end
should "allow accessing keys through attachment proxy" do
subject.image.size.should == 13661
subject.file.size.should == 68926
subject.image.type.should == "image/jpeg"
subject.file.type.should == "application/pdf"
subject.image.id.should_not be_nil
subject.file.id.should_not be_nil
subject.image.id.should be_instance_of(BSON::ObjectId)
subject.file.id.should be_instance_of(BSON::ObjectId)
end
should "proxy unknown methods to GridIO object" do
subject.image.files_id.should == subject.image_id
subject.image.content_type.should == 'image/jpeg'
subject.image.filename.should == 'mr_t.jpg'
subject.image.file_length.should == 13661
end
should "assign file name from path if original file name not available" do
subject.image_name.should == 'mr_t.jpg'
subject.file_name.should == 'unixref.pdf'
end
should "save attachment contents correctly" do
subject.file.read.should == @file.read
subject.image.read.should == @image.read
end
should "know that attachment exists" do
subject.image?.should be(true)
subject.file?.should be(true)
end
should "respond with false when asked if the attachment is blank?" do
subject.image.blank?.should be(false)
subject.file.blank?.should be(false)
end
should "clear assigned attachments so they don't get uploaded twice" do
Mongo::Grid.any_instance.expects(:put).never
subject.save
end
end
context "Assigning new attachments to embedded document" do
setup do
@asset = Asset.new
@doc = @asset.embedded_assets.build(:image => @image, :file => @file)
@asset.save!
rewind_files
end
subject { @doc }
should "assign GridFS content_type" do
grid.get(subject.image_id).content_type.should == 'image/jpeg'
grid.get(subject.file_id).content_type.should == 'application/pdf'
end
should "assign joint keys" do
subject.image_size.should == 13661
subject.file_size.should == 68926
subject.image_type.should == "image/jpeg"
subject.file_type.should == "application/pdf"
subject.image_id.should_not be_nil
subject.file_id.should_not be_nil
subject.image_id.should be_instance_of(BSON::ObjectId)
subject.file_id.should be_instance_of(BSON::ObjectId)
end
should "allow accessing keys through attachment proxy" do
subject.image.size.should == 13661
subject.file.size.should == 68926
subject.image.type.should == "image/jpeg"
subject.file.type.should == "application/pdf"
subject.image.id.should_not be_nil
subject.file.id.should_not be_nil
subject.image.id.should be_instance_of(BSON::ObjectId)
subject.file.id.should be_instance_of(BSON::ObjectId)
end
should "proxy unknown methods to GridIO object" do
subject.image.files_id.should == subject.image_id
subject.image.content_type.should == 'image/jpeg'
subject.image.filename.should == 'mr_t.jpg'
subject.image.file_length.should == 13661
end
should "assign file name from path if original file name not available" do
subject.image_name.should == 'mr_t.jpg'
subject.file_name.should == 'unixref.pdf'
end
should "save attachment contents correctly" do
subject.file.read.should == @file.read
subject.image.read.should == @image.read
end
should "know that attachment exists" do
subject.image?.should be(true)
subject.file?.should be(true)
end
should "respond with false when asked if the attachment is blank?" do
subject.image.blank?.should be(false)
subject.file.blank?.should be(false)
end
should "clear assigned attachments so they don't get uploaded twice" do
Mongo::Grid.any_instance.expects(:put).never
subject.save
end
end
context "Updating existing attachment" do
setup do
@doc = Asset.create(:file => @test1)
assert_no_grid_difference do
@doc.file = @test2
@doc.save!
end
rewind_files
end
subject { @doc }
should "not change attachment id" do
subject.file_id_changed?.should be(false)
end
should "update keys" do
subject.file_name.should == 'test2.txt'
subject.file_type.should == "text/plain"
subject.file_size.should == 5
end
should "update GridFS" do
grid.get(subject.file_id).filename.should == 'test2.txt'
grid.get(subject.file_id).content_type.should == 'text/plain'
grid.get(subject.file_id).file_length.should == 5
grid.get(subject.file_id).read.should == @test2.read
end
end
context "Updating existing attachment in embedded document" do
setup do
@asset = Asset.new
@doc = @asset.embedded_assets.build(:file => @test1)
@asset.save!
assert_no_grid_difference do
@doc.file = @test2
@doc.save!
end
rewind_files
end
subject { @doc }
should "update keys" do
subject.file_name.should == 'test2.txt'
subject.file_type.should == "text/plain"
subject.file_size.should == 5
end
should "update GridFS" do
grid.get(subject.file_id).filename.should == 'test2.txt'
grid.get(subject.file_id).content_type.should == 'text/plain'
grid.get(subject.file_id).file_length.should == 5
grid.get(subject.file_id).read.should == @test2.read
end
end
context "Updating document but not attachments" do
setup do
@doc = Asset.create(:image => @image)
@doc.update_attributes(:title => 'Updated')
@doc.reload
rewind_files
end
subject { @doc }
should "not affect attachment" do
subject.image.read.should == @image.read
end
should "update document attributes" do
subject.title.should == 'Updated'
end
end
context "Updating embedded document but not attachments" do
setup do
@asset = Asset.new
@doc = @asset.embedded_assets.build(:image => @image)
@doc.update_attributes(:title => 'Updated')
@asset.reload
@doc = @asset.embedded_assets.first
rewind_files
end
subject { @doc }
should "not affect attachment" do
subject.image.read.should == @image.read
end
should "update document attributes" do
subject.title.should == 'Updated'
end
end
context "Assigning file where file pointer is not at beginning" do
setup do
@image.read
@doc = Asset.create(:image => @image)
@doc.reload
rewind_files
end
subject { @doc }
should "rewind and correctly store contents" do
subject.image.read.should == @image.read
end
end
context "Setting attachment to nil" do
setup do
@doc = Asset.create(:image => @image)
rewind_files
end
subject { @doc }
should "delete attachment after save" do
assert_no_grid_difference { subject.image = nil }
assert_grid_difference(-1) { subject.save }
end
should "know that the attachment has been nullified" do
subject.image = nil
subject.image?.should be(false)
end
should "respond with true when asked if the attachment is nil?" do
subject.image = nil
subject.image.nil?.should be(true)
end
should "respond with true when asked if the attachment is blank?" do
subject.image = nil
subject.image.blank?.should be(true)
end
should "clear nil attachments after save and not attempt to delete again" do
Mongo::Grid.any_instance.expects(:delete).once
subject.image = nil
subject.save
Mongo::Grid.any_instance.expects(:delete).never
subject.save
end
should "clear id, name, type, size" do
subject.image = nil
subject.save
assert_nil subject.image_id
assert_nil subject.image_name
assert_nil subject.image_type
assert_nil subject.image_size
subject.reload
assert_nil subject.image_id
assert_nil subject.image_name
assert_nil subject.image_type
assert_nil subject.image_size
end
end
context "Setting attachment to nil on embedded document" do
setup do
@asset = Asset.new
@doc = @asset.embedded_assets.build(:image => @image)
@asset.save!
rewind_files
end
subject { @doc }
should "delete attachment after save" do
assert_no_grid_difference { subject.image = nil }
assert_grid_difference(-1) { subject.save }
end
should "know that the attachment has been nullified" do
subject.image = nil
subject.image?.should be(false)
end
should "respond with true when asked if the attachment is nil?" do
subject.image = nil
subject.image.nil?.should be(true)
end
should "respond with true when asked if the attachment is blank?" do
subject.image = nil
subject.image.blank?.should be(true)
end
should "clear nil attachments after save and not attempt to delete again" do
Mongo::Grid.any_instance.expects(:delete).once
subject.image = nil
subject.save
Mongo::Grid.any_instance.expects(:delete).never
subject.save
end
should "clear id, name, type, size" do
subject.image = nil
subject.save
assert_nil subject.image_id
assert_nil subject.image_name
assert_nil subject.image_type
assert_nil subject.image_size
s = subject._root_document.reload.embedded_assets.first
assert_nil s.image_id
assert_nil s.image_name
assert_nil s.image_type
assert_nil s.image_size
end
end
context "Retrieving attachment that does not exist" do
setup do
@doc = Asset.create
rewind_files
end
subject { @doc }
should "know that the attachment is not present" do
subject.image?.should be(false)
end
should "respond with true when asked if the attachment is nil?" do
subject.image.nil?.should be(true)
end
should "raise Mongo::GridFileNotFound" do
assert_raises(Mongo::GridFileNotFound) { subject.image.read }
end
end
context "Destroying a document" do
setup do
@doc = Asset.create(:image => @image)
rewind_files
end
subject { @doc }
should "remove files from grid fs as well" do
assert_grid_difference(-1) { subject.destroy }
end
end
context "Destroying an embedded document's _root_document" do
setup do
@asset = Asset.new
@doc = @asset.embedded_assets.build(:image => @image)
@doc.save!
rewind_files
end
subject { @doc }
should "remove files from grid fs as well" do
assert_grid_difference(-1) { subject._root_document.destroy }
end
end
# What about when an embedded document is removed?
context "Assigning file name" do
should "default to path" do
Asset.create(:image => @image).image.name.should == 'mr_t.jpg'
end
should "use original_filename if available" do
def @image.original_filename
'testing.txt'
end
doc = Asset.create(:image => @image)
assert_equal 'testing.txt', doc.image_name
end
end
context "Validating attachment presence" do
setup do
@model_class = Class.new do
include MongoMapper::Document
plugin Joint
attachment :file, :required => true
def self.name; "Foo"; end
end
end
should "work" do
model = @model_class.new
model.should_not be_valid
model.file = @file
model.should be_valid
model.file = nil
model.should_not be_valid
model.file = @image
model.should be_valid
end
end
context "Assigning joint io instance" do
setup do
io = Joint::IO.new({
:name => 'foo.txt',
:type => 'plain/text',
:content => 'This is my stuff'
})
@asset = Asset.create(:file => io)
end
should "work" do
@asset.file_name.should == 'foo.txt'
@asset.file_size.should == 16
@asset.file_type.should == 'plain/text'
@asset.file.read.should == 'This is my stuff'
end
end
context "A font file" do
setup do
@file = open_file('font.eot')
@doc = Asset.create(:file => @file)
end
subject { @doc }
should "assign joint keys" do
subject.file_size.should == 17610
subject.file_type.should == "application/octet-stream"
subject.file_id.should_not be_nil
subject.file_id.should be_instance_of(BSON::ObjectId)
end
end
context "A music file" do
setup do
@file = open_file('example.m4r')
@doc = Asset.create(:file => @file)
end
subject { @doc }
should "assign joint keys" do
subject.file_size.should == 50790
subject.file_type.should == "audio/mp4"
subject.file_id.should_not be_nil
subject.file_id.should be_instance_of(BSON::ObjectId)
end
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/test/helper.rb | test/helper.rb | require 'bundler/setup'
Bundler.setup(:default, 'test', 'development')
require 'tempfile'
require 'pp'
require 'shoulda'
require 'matchy'
require 'mocha'
require 'mongo_mapper'
require File.expand_path(File.dirname(__FILE__) + '/../lib/joint')
MongoMapper.database = "testing"
class Test::Unit::TestCase
def setup
MongoMapper.database.collections.each(&:remove)
end
def assert_difference(expression, difference = 1, message = nil, &block)
b = block.send(:binding)
exps = Array.wrap(expression)
before = exps.map { |e| eval(e, b) }
yield
exps.each_with_index do |e, i|
error = "#{e.inspect} didn't change by #{difference}"
error = "#{message}.\n#{error}" if message
after = eval(e, b)
assert_equal(before[i] + difference, after, error)
end
end
def assert_no_difference(expression, message = nil, &block)
assert_difference(expression, 0, message, &block)
end
def assert_grid_difference(difference=1, &block)
assert_difference("MongoMapper.database['fs.files'].find().count", difference, &block)
end
def assert_no_grid_difference(&block)
assert_grid_difference(0, &block)
end
end
class Asset
include MongoMapper::Document
plugin Joint
key :title, String
attachment :image
attachment :file
has_many :embedded_assets
end
class EmbeddedAsset
include MongoMapper::EmbeddedDocument
plugin Joint
key :title, String
attachment :image
attachment :file
end
class BaseModel
include MongoMapper::Document
plugin Joint
attachment :file
end
class Image < BaseModel; attachment :image end
class Video < BaseModel; attachment :video end
module JointTestHelpers
def all_files
[@file, @image, @image2, @test1, @test2]
end
def rewind_files
all_files.each { |file| file.rewind }
end
def open_file(name)
f = File.open(File.join(File.dirname(__FILE__), 'fixtures', name), 'r')
f.binmode
f
end
def grid
@grid ||= Mongo::Grid.new(MongoMapper.database)
end
def key_names
[:id, :name, :type, :size]
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/test/joint/test_io.rb | test/joint/test_io.rb | require 'helper'
class IOTest < Test::Unit::TestCase
context "#initialize" do
should "set attributes from hash" do
Joint::IO.new(:name => 'foo').name.should == 'foo'
end
end
should "default type to plain text" do
Joint::IO.new.type.should == 'plain/text'
end
should "default size to content size" do
content = 'This is my content'
Joint::IO.new(:content => content).size.should == content.size
end
should "alias path to name" do
Joint::IO.new(:name => 'foo').path.should == 'foo'
end
context "#read" do
should "return content" do
Joint::IO.new(:content => 'Testing').read.should == 'Testing'
end
end
context "#rewind" do
should "rewinds the io to position 0" do
io = Joint::IO.new(:content => 'Testing')
io.read.should == 'Testing'
io.read.should == ''
io.rewind
io.read.should == 'Testing'
end
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/test/joint/test_file_helpers.rb | test/joint/test_file_helpers.rb | require 'helper'
class FileHelpersTest < Test::Unit::TestCase
include JointTestHelpers
def setup
super
@image = open_file('mr_t.jpg')
end
def teardown
@image.close
end
context ".name" do
should "return original_filename" do
def @image.original_filename
'frank.jpg'
end
Joint::FileHelpers.name(@image).should == 'frank.jpg'
end
should "fall back to File.basename" do
Joint::FileHelpers.name(@image).should == 'mr_t.jpg'
end
end
context ".size" do
should "return size" do
def @image.size
25
end
Joint::FileHelpers.size(@image).should == 25
end
should "fall back to File.size" do
Joint::FileHelpers.size(@image).should == 13661
end
end
context ".type" do
should "return type if Joint::Io instance" do
file = Joint::IO.new(:type => 'image/jpeg')
Joint::FileHelpers.type(@image).should == 'image/jpeg'
end
should "fall back to Wand" do
Joint::FileHelpers.type(@image).should == 'image/jpeg'
end
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/lib/joint.rb | lib/joint.rb | require 'set'
require 'mime/types'
require 'wand'
require 'active_support/concern'
module Joint
extend ActiveSupport::Concern
included do
class_attribute :attachment_names
self.attachment_names = Set.new
include attachment_accessor_module
end
private
def self.blank?(str)
str.nil? || str !~ /\S/
end
end
require 'joint/class_methods'
require 'joint/instance_methods'
require 'joint/attachment_proxy'
require 'joint/io'
require 'joint/file_helpers'
| ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/lib/joint/io.rb | lib/joint/io.rb | require 'stringio'
module Joint
class IO
attr_accessor :name, :content, :type, :size
def initialize(attrs={})
attrs.each { |key, value| send("#{key}=", value) }
@type ||= 'plain/text'
end
def content=(value)
@io = StringIO.new(value || nil)
@size = value ? value.size : 0
end
def read(*args)
@io.read(*args)
end
def rewind
@io.rewind if @io.respond_to?(:rewind)
end
alias path name
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/lib/joint/version.rb | lib/joint/version.rb | module Joint
Version = '0.6.2'
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/lib/joint/file_helpers.rb | lib/joint/file_helpers.rb | module Joint
module FileHelpers
def self.name(file)
if file.respond_to?(:original_filename)
file.original_filename
else
File.basename(file.path)
end
end
def self.size(file)
if file.respond_to?(:size)
file.size
else
File.size(file)
end
end
def self.type(file)
return file.type if file.is_a?(Joint::IO)
Wand.wave(file.path, :original_filename => Joint::FileHelpers.name(file))
end
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/lib/joint/attachment_proxy.rb | lib/joint/attachment_proxy.rb | module Joint
class AttachmentProxy
def initialize(instance, name)
@instance, @name = instance, name
end
def id
@instance.send("#{@name}_id")
end
def name
@instance.send("#{@name}_name")
end
def size
@instance.send("#{@name}_size")
end
def type
@instance.send("#{@name}_type")
end
def nil?
!@instance.send("#{@name}?")
end
alias_method :blank?, :nil?
def grid_io
@grid_io ||= @instance.grid.get(id)
end
def method_missing(method, *args, &block)
grid_io.send(method, *args, &block)
end
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/lib/joint/class_methods.rb | lib/joint/class_methods.rb | module Joint
module ClassMethods
def attachment_accessor_module
@attachment_accessor_module ||= Module.new
end
def attachment(name, options = {})
options.symbolize_keys!
name = name.to_sym
self.attachment_names = attachment_names.dup.add(name)
after_save :save_attachments
before_save :nullify_nil_attachments_attributes
after_save :destroy_nil_attachments
before_destroy :destroy_all_attachments
key :"#{name}_id", ObjectId
key :"#{name}_name", String
key :"#{name}_size", Integer
key :"#{name}_type", String
validates_presence_of(name) if options[:required]
attachment_accessor_module.module_eval <<-EOC
def #{name}
@#{name} ||= AttachmentProxy.new(self, :#{name})
end
def #{name}?
!nil_attachments.has_key?(:#{name}) && send(:#{name}_id?)
end
def #{name}=(file)
if file.nil?
nil_attachments[:#{name}] = send("#{name}_id")
assigned_attachments.delete(:#{name})
else
send("#{name}_id=", BSON::ObjectId.new) if send("#{name}_id").nil?
send("#{name}_name=", Joint::FileHelpers.name(file))
send("#{name}_size=", Joint::FileHelpers.size(file))
send("#{name}_type=", Joint::FileHelpers.type(file))
assigned_attachments[:#{name}] = file
nil_attachments.delete(:#{name})
end
end
EOC
end
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
jnunemaker/joint | https://github.com/jnunemaker/joint/blob/c271e9a546450feebc8e36e0aef0a32b3b084dff/lib/joint/instance_methods.rb | lib/joint/instance_methods.rb | module Joint
def grid
@grid ||= Mongo::Grid.new(database)
end
private
def assigned_attachments
@assigned_attachments ||= {}
end
def nil_attachments
@nil_attachments ||= {}
end
# IO must respond to read and rewind
def save_attachments
assigned_attachments.each_pair do |name, io|
next unless io.respond_to?(:read)
io.rewind if io.respond_to?(:rewind)
grid.delete(send(name).id)
grid.put(io, {
:_id => send(name).id,
:filename => send(name).name,
:content_type => send(name).type,
})
end
assigned_attachments.clear
end
def nullify_nil_attachments_attributes
nil_attachments.each_key do |name|
send(:"#{name}_id=", nil)
send(:"#{name}_size=", nil)
send(:"#{name}_type=", nil)
send(:"#{name}_name=", nil)
end
end
def destroy_nil_attachments
nil_attachments.each_value do |id|
grid.delete(id)
end
nil_attachments.clear
end
def destroy_all_attachments
self.class.attachment_names.map { |name| grid.delete(send(name).id) }
end
end | ruby | MIT | c271e9a546450feebc8e36e0aef0a32b3b084dff | 2026-01-04T17:52:32.894919Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/spec/spec_helper.rb | spec/spec_helper.rb | require 'simplecov'
SimpleCov.start
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'huginn_agent'
require 'huginn_agent/cli'
require 'huginn_agent/spec_runner'
def capture(stream)
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").string
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end
RSpec.configure do |c|
c.filter_run focus: true
c.run_all_when_everything_filtered = true
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/spec/lib/huginn_agent_spec.rb | spec/lib/huginn_agent_spec.rb | require 'spec_helper'
describe HuginnAgent do
it 'has a version number' do
expect(HuginnAgent::VERSION).not_to be nil
end
context '#load_tasks' do
class Rake; end
before(:each) do
expect(Rake).to receive(:add_rakelib)
end
it 'sets default values for branch and remote' do
HuginnAgent.load_tasks
expect(HuginnAgent.branch).to eq('master')
expect(HuginnAgent.remote).to eq('https://github.com/huginn/huginn.git')
end
it "sets branch and remote based on the passed options" do
HuginnAgent.load_tasks(branch: 'test', remote: 'http://git.example.com')
expect(HuginnAgent.branch).to eq('test')
expect(HuginnAgent.remote).to eq('http://git.example.com')
end
end
context '#require!' do
before(:each) do
HuginnAgent.instance_variable_set(:@load_paths, [])
HuginnAgent.instance_variable_set(:@agent_paths, [])
end
it 'requires files passed to #load' do
HuginnAgent.load('/tmp/test.rb')
expect(HuginnAgent).to receive(:require).with('/tmp/test.rb')
HuginnAgent.require!
end
it 'requires files passwd to #register and assign adds the class name to Agents::TYPES' do
class Agent; TYPES = []; end
string_double= double('test_agent.rb', camelize: 'TestAgent')
expect(File).to receive(:basename).and_return(string_double)
HuginnAgent.register('/tmp/test_agent.rb')
expect(HuginnAgent).to receive(:require).with('/tmp/test_agent.rb')
HuginnAgent.require!
expect(Agent::TYPES).to eq(['Agents::TestAgent'])
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/spec/lib/huginn_agent/spec_runner_spec.rb | spec/lib/huginn_agent/spec_runner_spec.rb | require 'spec_helper'
describe HuginnAgent::SpecRunner do
unless defined?(Bundler)
class Bundler; def self.with_clean_env; yield end end
end
let(:runner) {HuginnAgent::SpecRunner.new }
it "detects the gem name" do
expect(runner.gem_name).to eq('huginn_agent')
end
context '#shell_out' do
it 'does not output anything without a specifing message' do
expect(runner).not_to receive(:puts)
runner.shell_out('pwd')
end
it "outputs the message and status information" do
output = capture(:stdout) { runner.shell_out('pwd', 'Testing') }
expect(output).to include('Testing')
expect(output).to include('OK')
expect(output).not_to include('FAIL')
end
it "output the called command on failure" do
output = capture(:stdout) {
expect { runner.shell_out('false', 'Testing') }.to raise_error(RuntimeError)
}
expect(output).to include('Testing')
expect(output).to include('FAIL')
expect(output).not_to include('OK')
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/spec/lib/huginn_agent/helper_spec.rb | spec/lib/huginn_agent/helper_spec.rb | require 'spec_helper'
describe HuginnAgent::Helper do
context '#open3' do
it "returns the exit status and output of the command" do
expect(HuginnAgent::Helper).not_to receive(:print)
(status, output) = HuginnAgent::Helper.open3("pwd")
expect(status).to eq(0)
expect(output).to eq("#{Dir.pwd}\n")
end
it "return 1 as the status for failing command" do
(status, output) = HuginnAgent::Helper.open3("false")
expect(status).to eq(1)
end
it "returns 1 when an IOError occurred" do
expect(IO).to receive(:select).and_raise(IOError)
(status, output) = HuginnAgent::Helper.open3("pwd")
expect(status).to eq(1)
expect(output).to eq('IOError IOError')
end
end
context '#exec' do
it "returns the exit status and output of the command" do
(status, output) = HuginnAgent::Helper.exec("pwd")
expect(status).to eq(0)
expect(output).to eq('')
end
it "return 1 as the status for failing command" do
(status, output) = HuginnAgent::Helper.exec("false")
expect(status).to eq(1)
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/spec/lib/huginn_agent/cli/new_spec.rb | spec/lib/huginn_agent/cli/new_spec.rb | require 'spec_helper'
require 'huginn_agent/cli/new'
describe HuginnAgent::CLI::New do
sandbox = File.expand_path(File.join(File.dirname(__FILE__), '../../../sandbox'))
let(:cli) { HuginnAgent::CLI.new }
let(:thor) { Thor.new }
before(:each) do
FileUtils.rm_rf(File.join(sandbox))
allow(Pathname).to receive(:pwd).and_return(Pathname.new(sandbox))
end
after(:each) { FileUtils.rm_rf(File.join(sandbox)) }
it "prefixes the gem name and copies the MIT license when told" do
expect(cli).to receive(:yes?).with(HuginnAgent::CLI::New::PREFIX_QUESTION) { true }
expect(cli).to receive(:yes?).with(HuginnAgent::CLI::New::MIT_QUESTION) { true }
capture(:stdout) { cli.new('test') }
expect(File.exist?(File.join(sandbox, 'huginn_test'))).to be_truthy
expect(File.exist?(File.join(sandbox, 'huginn_test', 'LICENSE.txt'))).to be_truthy
end
it "does not prefix the gem name and does notcopies the MIT license when told" do
expect(cli).to receive(:yes?).with(HuginnAgent::CLI::New::PREFIX_QUESTION) { false }
expect(cli).to receive(:yes?).with(HuginnAgent::CLI::New::MIT_QUESTION) { false }
capture(:stdout) { cli.new('test') }
expect(File.exist?(File.join(sandbox, 'huginn_test'))).to be_falsy
expect(File.exist?(File.join(sandbox, 'test'))).to be_truthy
expect(File.exist?(File.join(sandbox, 'test', 'LICENSE.txt'))).to be_falsy
end
it "asks to use a .env file" do
expect(cli).to receive(:yes?).with(HuginnAgent::CLI::New::PREFIX_QUESTION) { false }
expect(cli).to receive(:yes?).with(HuginnAgent::CLI::New::MIT_QUESTION) { false }
expect(cli).to receive(:ask).with(HuginnAgent::CLI::New::DOT_ENV_QUESTION) { 1 }
FileUtils.touch('.env')
capture(:stdout) { cli.new('test') }
FileUtils.rm('.env')
expect(File.exist?(File.join(sandbox, 'huginn_test'))).to be_falsy
expect(File.exist?(File.join(sandbox, 'test'))).to be_truthy
expect(File.exist?(File.join(sandbox, 'test', '.env'))).to be_truthy
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent.rb | lib/huginn_agent.rb | require 'huginn_agent/version'
class HuginnAgent
class << self
attr_accessor :branch, :remote
def load_tasks(options = {})
@branch = options[:branch] || 'master'
@remote = options[:remote] || 'https://github.com/huginn/huginn.git'
Rake.add_rakelib File.join(File.expand_path('../', __FILE__), 'tasks')
end
def load(*paths)
paths.each do |path|
load_paths << path
end
end
def register(*paths)
paths.each do |path|
agent_paths << path
end
end
def require!
load_paths.each do |path|
require path
end
agent_paths.each do |path|
if Rails.autoloaders.zeitwerk_enabled?
setup_zeitwerk_loader path
else
require_dependency path
end
Agent::TYPES << "Agents::#{File.basename(path.to_s).camelize}"
end
end
private
def load_paths
@load_paths ||= []
end
def agent_paths
@agent_paths ||= []
end
def setup_zeitwerk_loader(gem_path)
gem, _, mod_path = gem_path.partition('/')
gemspec = Gem::Specification.find_by_name(gem)
gem_dir = Pathname.new(gemspec.gem_dir)
module_dir = gem_dir + gemspec.require_paths[0] + gem
loader = Zeitwerk::Loader.new
loader.tag = gem
loader.push_dir(module_dir, namespace: Agents)
loader.setup
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/version.rb | lib/huginn_agent/version.rb | class HuginnAgent
VERSION = '0.6.1'
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/spec_runner.rb | lib/huginn_agent/spec_runner.rb | require 'huginn_agent/helper'
class HuginnAgent
class SpecRunner
attr_reader :gem_name
def initialize
@gem_name = File.basename(Dir['*.gemspec'].first, '.gemspec')
$stdout.sync = true
end
def clone
unless File.exist?('spec/huginn/.git')
shell_out "git clone #{HuginnAgent.remote} -b #{HuginnAgent.branch} spec/huginn", 'Cloning huginn source ...'
end
end
def reset
Dir.chdir('spec/huginn') do
shell_out "git fetch && git reset --hard origin/#{HuginnAgent.branch}", 'Resetting Huginn source ...'
end
end
def patch
Dir.chdir('spec/huginn') do
open('Gemfile', 'a') do |f|
f.puts File.read(File.join(__dir__, 'patches/gemfile_helper.rb'))
end
end
end
def bundle
if File.exist?('.env')
shell_out "cp .env spec/huginn"
end
Dir.chdir('spec/huginn') do
if !File.exist?('.env')
shell_out "cp .env.example .env"
end
shell_out "bundle install --without development production -j 4", 'Installing ruby gems ...'
end
end
def database
Dir.chdir('spec/huginn') do
shell_out('bundle exec rake db:create db:migrate', 'Creating database ...')
end
end
def spec
Dir.chdir('spec/huginn') do
shell_out "bundle exec rspec -r #{File.join(__dir__, 'patches/coverage.rb')} --pattern '../**/*_spec.rb' --exclude-pattern './spec/**/*_spec.rb'", 'Running specs ...', true
end
end
def shell_out(command, message = nil, streaming_output = false)
print message if message
(status, output) = Bundler.with_clean_env do
ENV['ADDITIONAL_GEMS'] = "#{gem_name}(path: ../../)"
ENV['RAILS_ENV'] = 'test'
if streaming_output
HuginnAgent::Helper.exec(command)
else
HuginnAgent::Helper.open3(command)
end
end
if status == 0
puts "\e[32m [OK]\e[0m" if message
else
puts "\e[31m [FAIL]\e[0m" if message
puts "Tried executing '#{command}'"
puts output
fail
end
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/cli.rb | lib/huginn_agent/cli.rb | require 'thor'
require 'huginn_agent/version'
class HuginnAgent
class CLI < Thor
include Thor::Actions
desc "new AGENT_GEM_NAME", "Create a skeleton for creating a new Huginn agent"
def new(name)
require 'huginn_agent/cli/new'
New.new(options, name, self).run
end
def self.source_root
File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/helper.rb | lib/huginn_agent/helper.rb | require 'open3'
class HuginnAgent
class Helper
def self.open3(command)
output = ""
status = Open3.popen3(ENV, "#{command} 2>&1") do |stdin, stdout, _stderr, wait_thr|
stdin.close
until stdout.eof do
next unless IO.select([stdout])
output << stdout.read_nonblock(1024)
end
wait_thr.value
end
[status.exitstatus, output]
rescue IOError => e
return [1, "#{e} #{e.message}"]
end
def self.exec(command)
print "\n"
[system(ENV, command) == true ? 0 : 1, '']
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/spec_helper.rb | lib/huginn_agent/spec_helper.rb | Dir[File.join(File.expand_path('../'), "support/**/*.rb")].each { |f| require f }
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/patches/coverage.rb | lib/huginn_agent/patches/coverage.rb | require 'simplecov'
if !ENV['COVERAGE']
require 'coveralls'
module Coveralls
module Configuration
def self.root
File.expand_path(File.join(Dir.pwd, '../..'))
end
end
end
end
SimpleCov.root File.expand_path(File.join(Dir.pwd, '../..'))
SimpleCov.start :rails do
add_filter do |src|
!(src.filename =~ /^#{SimpleCov.root}\/lib\//)
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/patches/gemfile_helper.rb | lib/huginn_agent/patches/gemfile_helper.rb |
# This Gemfile modification was generated by the `rake prepare` command
#
class GemfileHelper
def self.parse_huginn_agent_gems(dependencies)
base_path = File.expand_path('../../../', __FILE__)
gemspec = Dir["#{base_path}/*.gemspec"].first
previous_gems = Hash[dependencies.map { |dep| [dep.name, dep] }]
Gem::Specification.load(gemspec).development_dependencies.each do |args|
previous_gem = previous_gems[args.name]
if previous_gem
abort "Gem #{args.to_s} in #{gemspec} conflicts with huginn/Gemfile" unless previous_gem.match?(args.to_spec)
else
yield args.name, *args.requirements_list
end
end
end
end
GemfileHelper.parse_huginn_agent_gems(dependencies) do |args|
gem *args
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
huginn/huginn_agent | https://github.com/huginn/huginn_agent/blob/59f0facaf640c1f5cafb0c4f3547519dcf895753/lib/huginn_agent/cli/new.rb | lib/huginn_agent/cli/new.rb | require 'pathname'
require 'huginn_agent/helper'
class HuginnAgent
class CLI::New
PREFIX_QUESTION = "We recommend prefixing all Huginn agent gem names with 'huginn_' to make them easily discoverable.\nPrefix gem name with 'huginn_'?".freeze
MIT_QUESTION = "Do you want to license your code permissively under the MIT license?".freeze
DOT_ENV_QUESTION = 'Which .env file do you want to use?'.freeze
attr_reader :options, :gem_name, :thor, :target
def initialize(options, gem_name, thor)
@options = options
@thor = thor
if !gem_name.start_with?('huginn_') &&
thor.yes?(PREFIX_QUESTION)
gem_name = "huginn_#{gem_name}"
end
@target = Pathname.pwd.join(gem_name)
@gem_name = target.basename.to_s
end
def run
thor.say "Creating Huginn agent '#{gem_name}'"
agent_file_name = gem_name.gsub('huginn_', '')
namespaced_path = gem_name.tr('-', '/')
constant_name = gem_name.split('_')[1..-1].map{|p| p[0..0].upcase + p[1..-1] unless p.empty?}.join
constant_name = constant_name.split('-').map{|q| q[0..0].upcase + q[1..-1] }.join('::') if constant_name =~ /-/
git_user_name = `git config user.name`.chomp
git_user_email = `git config user.email`.chomp
opts = {
:gem_name => gem_name,
:agent_file_name => agent_file_name,
:namespaced_path => namespaced_path,
:constant_name => constant_name,
:author => git_user_name.empty? ? "TODO: Write your name" : git_user_name,
:email => git_user_email.empty? ? "TODO: Write your email address" : git_user_email,
}
templates = {
"Gemfile.tt" => "Gemfile",
"gitignore.tt" => ".gitignore",
"lib/new_agent.rb.tt" => "lib/#{namespaced_path}.rb",
"lib/new_agent/new_agent.rb.tt" => "lib/#{namespaced_path}/#{agent_file_name}.rb",
"spec/new_agent_spec.rb.tt" => "spec/#{agent_file_name}_spec.rb",
"newagent.gemspec.tt" => "#{gem_name}.gemspec",
"Rakefile.tt" => "Rakefile",
"README.md.tt" => "README.md",
"travis.yml.tt" => ".travis.yml"
}
if thor.yes?(MIT_QUESTION)
opts[:mit] = true
templates.merge!("LICENSE.txt.tt" => "LICENSE.txt")
end
templates.each do |src, dst|
thor.template("newagent/#{src}", target.join(dst), opts)
end
thor.say "To run the specs of your agent you need to add a .env which configures the database for Huginn"
possible_paths = Dir['.env', './huginn/.env', '~/huginn/.env']
if possible_paths.length > 0
thor.say 'Found possible preconfigured .env files please choose which one you want to use'
possible_paths.each_with_index do |path, i|
thor.say "#{i+1} #{path}"
end
if (i = thor.ask(DOT_ENV_QUESTION).to_i) != 0
path = possible_paths[i-1]
`cp #{path} #{target}`
thor.say "Copied '#{path}' to '#{target}'"
end
end
thor.say "Initializing git repo in #{target}"
Dir.chdir(target) { `git init`; `git add .` }
thor.say 'Installing dependencies'
Dir.chdir(target) { HuginnAgent::Helper.open3('bundle install') }
end
end
end
| ruby | MIT | 59f0facaf640c1f5cafb0c4f3547519dcf895753 | 2026-01-04T17:52:34.055670Z | false |
jondruse/screeninator | https://github.com/jondruse/screeninator/blob/e0da51a730231e45081d0841c157216a8e1f2fe9/test/helper.rb | test/helper.rb | require 'rubygems'
require 'test/unit'
require 'shoulda'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'screeninator'
class Test::Unit::TestCase
end
| ruby | MIT | e0da51a730231e45081d0841c157216a8e1f2fe9 | 2026-01-04T17:52:34.353252Z | false |
jondruse/screeninator | https://github.com/jondruse/screeninator/blob/e0da51a730231e45081d0841c157216a8e1f2fe9/test/test_screeninator.rb | test/test_screeninator.rb | require 'helper'
class TestScreeninator < Test::Unit::TestCase
should "probably rename this file and start testing for real" do
flunk "hey buddy, you should probably rename this file and start testing for real"
end
end
| ruby | MIT | e0da51a730231e45081d0841c157216a8e1f2fe9 | 2026-01-04T17:52:34.353252Z | false |
jondruse/screeninator | https://github.com/jondruse/screeninator/blob/e0da51a730231e45081d0841c157216a8e1f2fe9/lib/screeninator.rb | lib/screeninator.rb | require 'yaml'
require 'ostruct'
require 'erb'
require 'screeninator/helper'
require 'screeninator/cli'
require 'screeninator/config_writer'
module Screeninator
USER_CONFIG = "#{ENV["HOME"]}/.screeninator/defaults/default.yml"
USER_SCREEN_CONFIG = "#{ENV["HOME"]}/.screeninator/defaults/screen_config.screen"
end
| ruby | MIT | e0da51a730231e45081d0841c157216a8e1f2fe9 | 2026-01-04T17:52:34.353252Z | false |
jondruse/screeninator | https://github.com/jondruse/screeninator/blob/e0da51a730231e45081d0841c157216a8e1f2fe9/lib/screeninator/config_writer.rb | lib/screeninator/config_writer.rb | module Screeninator
class ConfigWriter
include Screeninator::Helper
def self.write_aliases(aliases)
File.open("#{ENV["HOME"]}/.screeninator/scripts/screeninator", 'w') {|f| f.write(aliases.join("\n")) }
end
def initialize(filename)
@filename = filename
@file_path = "#{root_dir}#{@filename}.yml"
process_config!
end
def write!
if File.exists?(USER_SCREEN_CONFIG)
template = USER_SCREEN_CONFIG
else
template = "#{File.dirname(__FILE__)}/assets/screen_config.screen"
end
erb = ERB.new(IO.read(template)).result(binding)
config_path = "#{root_dir}#{@filename}.screen"
tmp = File.open(config_path, 'w') {|f| f.write(erb) }
@project_name.gsub!(" ", "_")
check = "screen -ls | grep #{@project_name}"
attch = "screen -dr #{@project_name}"
start = "screen -c #{config_path} -S #{@project_name}"
%Q{alias start_#{@filename}='if [[ -n `#{check}` ]] ; then `#{attch}` ; else `#{start}`; fi'}
end
private
def root_dir
"#{ENV["HOME"]}/.screeninator/"
end
def process_config!
raise ArgumentError.new("#{@file_path} is not valid YAML!") unless yaml = YAML.load(File.read(@file_path))
raise ArgumentError.new("Your configuration file should include some tabs.") if yaml["tabs"].nil?
raise ArgumentError.new("Your configuration file didn't specify a 'project_root'") if yaml["project_root"].nil?
raise ArgumentError.new("Your configuration file didn't specify a 'project_name'") if yaml["project_name"].nil?
@escape = if yaml["escape"]
yaml["escape"] == "tick" ? "``" : yaml["escape"]
else
nil
end
@project_name = yaml["project_name"]
@project_root = yaml["project_root"]
@tabs = []
yaml["tabs"].each do |tab|
t = OpenStruct.new
t.name = tab.keys.first
value = tab.values.first
t.stuff = if value.is_a?(Array)
value.join(" && ")
else
value
end
@tabs << t
end
end
def write_alias(stuff)
File.open("#{root_dir}scripts/#{@filename}", 'w') {|f| f.write(stuff) }
end
end
end
| ruby | MIT | e0da51a730231e45081d0841c157216a8e1f2fe9 | 2026-01-04T17:52:34.353252Z | false |
jondruse/screeninator | https://github.com/jondruse/screeninator/blob/e0da51a730231e45081d0841c157216a8e1f2fe9/lib/screeninator/cli.rb | lib/screeninator/cli.rb | require 'fileutils'
# Author:: Jon Druse (mailto:jon@jondruse.com)
#
# = Description
#
# This class is where each screeninator command is implemented.
#
# == Change History
# * 09/20/10:: created Jon Druse (mailto:jon@jondruse.com)
# * 03/15/11:: renmaed usage to help. adding option parser
module Screeninator
class Cli
class << self
include Screeninator::Helper
def start(*args)
begin
if args.empty?
self.help
else
self.send(args.shift, *args)
end
rescue NoMethodError => e
puts e
self.help
end
end
# print the usage string, this is a fall through method.
def help
puts HELP_TEXT
end
# Open a config file, it's created if it doesn't exist already.
def open(*args)
@name = args.shift
FileUtils.mkdir_p(root_dir+"scripts")
config_path = "#{root_dir}#{@name}.yml"
unless File.exists?(config_path)
template = File.exists?(user_config) ? user_config : "#{File.dirname(__FILE__)}/assets/sample.yml"
erb = ERB.new(File.read(template)).result(binding)
tmp = File.open(config_path, 'w') {|f| f.write(erb) }
end
system("$EDITOR #{config_path}")
update(@name)
end
def copy(*args)
@copy = args.shift
@name = args.shift
@config_to_copy = "#{root_dir}#{@copy}.yml"
exit!("Project #{@copy} doesn't exist!") unless File.exists?(@config_to_copy)
exit!("You must specify a name for the new project") unless @name
file_path = "#{root_dir}#{@name}.yml"
if File.exists?(file_path)
confirm!("#{@name} already exists, would you like to overwrite it? (type yes or no):") do
FileUtils.rm(file_path)
puts "Overwriting #{@name}"
end
end
open(@name)
end
def delete(*args)
puts "warning: passing multiple arguments to delete will be ignored" if args.size > 1
filename = args.shift
files = Dir["#{root_dir}#{filename}*"]
unless files.empty?
confirm!("Are you sure you want to delete #{filename}? (type yes or no):") do
FileUtils.rm(files)
puts "Deleted #{filename}"
end
end
update
end
def implode(*args)
exit!("delete_all doesn't accapt any arguments!") unless args.empty?
confirm!("Are you sure you want to delete all screeninator configs? (type yes or no):") do
FileUtils.remove_dir(root_dir)
puts "Deleted #{root_dir}"
end
end
def list(*args)
puts "screeninator configs:"
list
end
def info(*args)
puts "screeninator configs:"
list(true)
end
def update(*args)
aliases = []
Dir["#{root_dir}*.yml"].each do |path|
begin
path = File.basename(path, '.yml')
config_name = path.split("/").last
begin; FileUtils.rm("#{path}.screen"); rescue; end
aliases << Screeninator::ConfigWriter.new(path).write!
rescue ArgumentError => e
puts e
end
end
Screeninator::ConfigWriter.write_aliases(aliases)
end
def customize(*args)
@type = args.shift
@action = args.shift
if !['config','template'].include?(@type)
puts "Usage: screeninator customize [config|template]"
puts "config - This is the default YAML config file to use."
puts "template - This is the default screen config template, complete with ERB"
exit
end
FileUtils.mkdir_p(root_dir+"defaults")
path = case @type
when "config"; USER_CONFIG
when "template"; USER_SCREEN_CONFIG
end
if @action.nil?
system("$EDITOR #{path}")
end
if @action == "delete"
confirm!("Are you sure you want to delete #{path}? (type yes or no):") do
FileUtils.rm(path)
puts "Deleted #{path}"
end
end
end
private
def root_dir
dir = "#{ENV["HOME"]}/.screeninator/"
end
def sample_config
"#{File.dirname(__FILE__)}/assets/sample.yml"
end
def user_config
@config_to_copy || USER_CONFIG
end
def user_screen_config
USER_SCREEN_CONFIG
end
def list(verbose=false)
Dir["#{root_dir}**"].each do |path|
next unless verbose || File.extname(path) == ".yml"
path = path.gsub(root_dir, '').gsub('.yml','') unless verbose
puts " #{path}"
end
end
end
end
end
| ruby | MIT | e0da51a730231e45081d0841c157216a8e1f2fe9 | 2026-01-04T17:52:34.353252Z | false |
jondruse/screeninator | https://github.com/jondruse/screeninator/blob/e0da51a730231e45081d0841c157216a8e1f2fe9/lib/screeninator/helper.rb | lib/screeninator/helper.rb | module Screeninator
module Helper
help = ["Usage: screeninator ACTION [Args]\n\n"]
help << "Available Commands:\n\n"
help << "open CONFIG_NAME".ljust(40) + "Open's the config file in $EDITOR. If it doesn't exist, it will be created."
help << "copy CONFIG_NAME NEW_CONFIG".ljust(40) + "Copy an existing config into a new one."
help << "list".ljust(40) + "List all your current config files."
help << "info".ljust(40) + "List full path of all config files, their compiled versions, and bash scripts."
help << "customize [config|template] [delete]".ljust(40) + "Write your own default YML config or screen template."
help << "update [CONFIG_NAME, CONFIG_NAME]".ljust(40) + "Recompile all config files. Helpful if you edit them without using 'screeninator open'."
help << "implode".ljust(40) + "Destroy all configs, compiled configs, and bash scripts."
HELP_TEXT = help.join("\n")
def exit!(msg)
puts msg
Kernel.exit(1)
end
def confirm!(msg)
puts msg
if %w(yes Yes YES y).include?(STDIN.gets.chop)
yield
else
exit! "Aborting."
end
end
end
end | ruby | MIT | e0da51a730231e45081d0841c157216a8e1f2fe9 | 2026-01-04T17:52:34.353252Z | false |
inkel/fallen | https://github.com/inkel/fallen/blob/68a2f36cdab82f43b24e8f4ce789deb921d90212/examples/azazel_cli.rb | examples/azazel_cli.rb | require_relative "../lib/fallen"
require_relative "../lib/fallen/cli"
module Azazel
extend Fallen
extend Fallen::CLI
def self.run
while running?
puts "My name is Legion"
sleep 666
end
end
def self.usage
puts fallen_usage
end
end
case Clap.run(ARGV, Azazel.cli).first
when "start"
Azazel.start!
when "stop"
Azazel.stop!
else
Azazel.usage
end
| ruby | Unlicense | 68a2f36cdab82f43b24e8f4ce789deb921d90212 | 2026-01-04T17:52:26.471326Z | false |
inkel/fallen | https://github.com/inkel/fallen/blob/68a2f36cdab82f43b24e8f4ce789deb921d90212/examples/azazel.rb | examples/azazel.rb | require_relative "../lib/fallen"
module Azazel
extend Fallen
def self.run
while running?
puts "My name is Legion"
sleep 666
end
end
end
Azazel.start!
| ruby | Unlicense | 68a2f36cdab82f43b24e8f4ce789deb921d90212 | 2026-01-04T17:52:26.471326Z | false |
inkel/fallen | https://github.com/inkel/fallen/blob/68a2f36cdab82f43b24e8f4ce789deb921d90212/lib/fallen.rb | lib/fallen.rb | module Fallen
@running = false
@pidfile = nil
@stdin = nil
@stdout = nil
@stderr = nil
# Detachs this fallen angel from current process and runs it in
# background
#
# @note Unless `STDIN`, `STDOUT` or `STDERR` are redirected to a
# file, these will be redirected to `/dev/null`
def daemonize!
Process.daemon true, (@stdin || @stdout || @stderr)
end
# Changes the working directory
#
# All paths will be relative to the working directory unless they're
# specified as absolute paths.
#
# @param [String] path of the new workng directory
def chdir! path
Dir.chdir File.absolute_path(path)
end
# Path where the PID file will be created
def pid_file path
@pid_file = File.absolute_path(path)
end
# Reopens `STDIN` for reading from `path`
#
# This path is relative to the working directory unless an absolute
# path is given.
def stdin path
@stdin = File.absolute_path(path)
STDIN.reopen @stdin
end
# Reopens `STDOUT` for writing to `path`
#
# This path is relative to the working directory unless an absolute
# path is given.
def stdout path
@stdout = File.absolute_path(path)
STDOUT.reopen @stdout, "a"
STDOUT.sync = true
end
# Reopens `STDERR` for writing to `path`
#
# This path is relative to the working directory unless an absolute
# path is given.
def stderr path
@stderr = File.absolute_path(path)
STDERR.reopen @stderr, "a"
STDERR.sync = true
end
# Returns `true` if the fallen angel is running
def running?
@running
end
# Brings the fallen angel to life
#
# If a PID file was provided it will try to store the current
# PID. If this files exists it will try to check if the stored PID
# is already running, in which case `Fallen` will exit with an error
# code.
def start!
if @pid_file && File.exists?(@pid_file)
pid = File.read(@pid_file).strip
begin
Process.kill 0, pid.to_i
STDERR.puts "Daemon is already running with PID #{pid}"
exit 2
rescue Errno::ESRCH
run!
end
else
run!
end
end
# Runs the fallen angel
#
# This will set up `INT` & `TERM` signal handlers to stop execution
# properly. When this signal handlers are called it will also call
# the `stop` callback method and delete the pid file
def run!
save_pid_file
@running = true
trap(:INT) { interrupt }
trap(:TERM) { interrupt }
run
end
# Handles an interrupt (`SIGINT` or `SIGTERM`) properly as it
# deletes the pid file and calles the `stop` method.
def interrupt
@running = false
File.delete @pid_file if @pid_file && File.exists?(@pid_file)
stop
end
# Stops fallen angel execution
#
# This method only works when a PID file is given, otherwise it will
# exit with an error.
def stop!
if @pid_file && File.exists?(@pid_file)
pid = File.read(@pid_file).strip
begin
Process.kill :INT, pid.to_i
File.delete @pid_file
rescue Errno::ESRCH
STDERR.puts "No daemon is running with PID #{pid}"
exit 3
end
else
STDERR.puts "Couldn't find a PID file"
exit 1
end
end
# Callback method to be run when fallen angel stops
def stop; end
private
# Save the falen angel PID to the PID file specified in `pid_file`
def save_pid_file
File.open(@pid_file, "w") do |fp|
fp.write(Process.pid)
end if @pid_file
end
end
| ruby | Unlicense | 68a2f36cdab82f43b24e8f4ce789deb921d90212 | 2026-01-04T17:52:26.471326Z | false |
inkel/fallen | https://github.com/inkel/fallen/blob/68a2f36cdab82f43b24e8f4ce789deb921d90212/lib/fallen/cli.rb | lib/fallen/cli.rb | require "clap"
module Fallen::CLI
def cli
{
"-D" => self.method(:daemonize!),
"-C" => self.method(:chdir!),
"-P" => self.method(:pid_file),
"-out" => self.method(:stdout),
"-err" => self.method(:stderr),
"-in" => self.method(:stdin)
}
end
def fallen_usage
<<-USAGE
Fallen introduced command line arguments:
-D Daemonize this process
-C Change directory.
-P Path to PID file. Only used in daemonized process.
-out Path to redirect STDOUT.
-err Path to redirect STDERR.
-in Path to redirect STDIN.
USAGE
end
end
| ruby | Unlicense | 68a2f36cdab82f43b24e8f4ce789deb921d90212 | 2026-01-04T17:52:26.471326Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/helpers/spree/reviews_helper.rb | app/helpers/spree/reviews_helper.rb | module Spree::ReviewsHelper
# This method is unused in the spree_reviews extension
# by default, but could be used in custom view setups.
def star(the_class)
content_tag(:span, ' ✮ '.html_safe, class: the_class)
end
# This method is unused in the spree_reviews extension
# by default, but could be used in custom view setups.
def mk_stars(m)
(1..5).collect { |n| n <= m ? star('lit') : star('unlit') }.join
end
def txt_stars(n, show_out_of = true)
res = Spree.t(:star, count: n)
res += " #{Spree.t('out_of_5')}" if show_out_of
res
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/controllers/spree/reviews_controller.rb | app/controllers/spree/reviews_controller.rb | module Spree
class ReviewsController < Spree::StoreController
helper Spree::BaseHelper
before_action :load_product, only: [:index, :new, :create]
before_action :init_pagination, only: [:index]
def index
@approved_reviews = Spree::Review.default_approval_filter.where(product: @product).page(@pagination_page).per(@pagination_per_page)
@title = "#{@product.name} #{Spree.t(:reviews)}"
end
def new
@review = Spree::Review.new(product: @product)
authorize! :create, @review
end
def create
params[:review][:rating].sub!(/\s*[^0-9]*\z/, '') unless params[:review][:rating].blank?
@review = Spree::Review.new(review_params)
@review.product = @product
@review.user = spree_current_user if spree_user_signed_in?
@review.ip_address = request.remote_ip
@review.locale = I18n.locale.to_s if Spree::Reviews::Config[:track_locale]
authorize! :create, @review
if @review.save
flash[:notice] = Spree.t(:review_successfully_submitted)
redirect_to spree.product_path(@product)
else
render :new
end
end
private
def load_product
@product = Spree::Product.friendly.find(params[:product_id])
end
def permitted_review_attributes
permitted_attributes.review_attributes
end
def review_params
params.require(:review).permit(permitted_review_attributes)
end
def init_pagination
@pagination_page = params[:page].present? ? params[:page].to_i : 1
@pagination_per_page = params[:per_page].present? ? params[:per_page].to_i : Spree::Reviews::Config[:paginate_size]
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/controllers/spree/feedback_reviews_controller.rb | app/controllers/spree/feedback_reviews_controller.rb | module Spree
class FeedbackReviewsController < Spree::StoreController
helper Spree::BaseHelper
before_action :sanitize_rating, only: :create
before_action :load_review, only: :create
def create
if @review.present?
@feedback_review = @review.feedback_reviews.new(feedback_review_params)
@feedback_review.user = spree_current_user
@feedback_review.locale = I18n.locale.to_s if Spree::Reviews::Config[:track_locale]
authorize! :create, @feedback_review
@feedback_review.save
end
respond_to do |format|
format.html { redirect_back(fallback_location: root_path) }
format.js { render action: :create }
end
end
protected
def load_review
@review ||= Spree::Review.find_by_id!(params[:review_id])
end
def permitted_feedback_review_attributes
permitted_attributes.feedback_review_attributes
end
def feedback_review_params
params.require(:feedback_review).permit(permitted_feedback_review_attributes)
end
def sanitize_rating
params[:feedback_review][:rating].to_s.sub!(/\s*[^0-9]*\z/, '') unless params[:feedback_review] && params[:feedback_review][:rating].blank?
end
def redirect_back(fallback_location:)
if Rails.gem_version >= Gem::Version.new('5.x')
super
else
redirect_to :back
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/controllers/spree/products_controller_decorator.rb | app/controllers/spree/products_controller_decorator.rb | module Spree
module ProductsControllerDecorator
def self.prepended(base)
base.helper Spree::ReviewsHelper
end
::Spree::ProductsController.prepend self if ::Spree::Core::Engine.frontend_available? && ::Spree::ProductsController.included_modules.exclude?(self)
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/controllers/spree/admin/reviews_controller.rb | app/controllers/spree/admin/reviews_controller.rb | module Spree
module Admin
class ReviewsController < ResourceController
helper Spree::ReviewsHelper
def index
@reviews = collection
end
def approve
review = Spree::Review.find(params[:id])
if review.update_attribute(:approved, true)
flash[:notice] = Spree.t(:info_approve_review)
else
flash[:error] = Spree.t(:error_approve_review)
end
redirect_to admin_reviews_path
end
def edit
return if @review.product
flash[:error] = Spree.t(:error_no_product)
redirect_to admin_reviews_path
end
private
def collection
params[:q] ||= {}
@search = Spree::Review.ransack(params[:q])
@collection = @search.result.includes([:product, :user, :feedback_reviews]).page(params[:page]).per(params[:per_page])
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/controllers/spree/admin/review_settings_controller.rb | app/controllers/spree/admin/review_settings_controller.rb | module Spree
module Admin
class ReviewSettingsController < ResourceController
def update
settings = Spree::ReviewSetting.new
preferences = params&.key?(:preferences) ? params.delete(:preferences) : params
preferences.each do |name, value|
next unless settings.has_preference? name
settings[name] = value
end
flash[:success] = Spree.t(:successfully_updated, resource: Spree.t(:review_settings, scope: :spree_reviews))
redirect_to edit_admin_review_settings_path
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/controllers/spree/admin/feedback_reviews_controller.rb | app/controllers/spree/admin/feedback_reviews_controller.rb | module Spree
module Admin
class FeedbackReviewsController < ResourceController
belongs_to 'spree/review'
def index
@collection = parent.feedback_reviews
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/models/spree/review.rb | app/models/spree/review.rb | class Spree::Review < ActiveRecord::Base
belongs_to :product, touch: true
belongs_to :user, class_name: Spree.user_class.to_s
has_many :feedback_reviews
after_save :recalculate_product_rating, if: :approved?
after_destroy :recalculate_product_rating
validates :name, :review, presence: true
validates :rating, numericality: {
only_integer: true,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 5,
message: :you_must_enter_value_for_rating
}
default_scope { order('spree_reviews.created_at DESC') }
scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
scope :approved, -> { where(approved: true) }
scope :not_approved, -> { where(approved: false) }
scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }
def feedback_stars
return 0 if feedback_reviews.size <= 0
((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
end
def recalculate_product_rating
product.recalculate_rating if product.present?
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/models/spree/reviews_ability.rb | app/models/spree/reviews_ability.rb | class Spree::ReviewsAbility
include CanCan::Ability
def initialize(user)
review_ability_class = self.class
can :create, Spree::Review do
review_ability_class.allow_anonymous_reviews? || !user.email.blank?
end
can :create, Spree::FeedbackReview do
review_ability_class.allow_anonymous_reviews? || !user.email.blank?
end
end
def self.allow_anonymous_reviews?
!Spree::Reviews::Config[:require_login]
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/models/spree/feedback_review.rb | app/models/spree/feedback_review.rb | class Spree::FeedbackReview < ActiveRecord::Base
belongs_to :user, class_name: Spree.user_class.to_s
belongs_to :review, dependent: :destroy
validates :review, presence: true
validates :rating, numericality: {
only_integer: true,
greater_than_or_equal_to: 1,
less_than_or_equal_to: 5,
message: :you_must_enter_value_for_rating
}
default_scope { most_recent_first }
scope :most_recent_first, -> { order('spree_feedback_reviews.created_at DESC') }
scope :localized, ->(lc) { where('spree_feedback_reviews.locale = ?', lc) }
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/models/spree/product_decorator.rb | app/models/spree/product_decorator.rb | # Add access to reviews/ratings to the product model
module Spree
module ProductDecorator
def self.prepended(base)
base.has_many :reviews
end
def stars
avg_rating.try(:round) || 0
end
def recalculate_rating
self[:reviews_count] = reviews.reload.approved.count
self[:avg_rating] = if reviews_count > 0
reviews.approved.sum(:rating).to_f / reviews_count
else
0
end
save
end
::Spree::Product.prepend self if ::Spree::Product.included_modules.exclude?(self)
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/models/spree/review_setting.rb | app/models/spree/review_setting.rb | module Spree
class ReviewSetting < Preferences::Configuration
# Include non-approved reviews in (public) listings.
preference :include_unapproved_reviews, :boolean, default: false
# Control how many reviews are shown in summaries etc.
preference :preview_size, :integer, default: 3
# Show a reviewer's email address.
preference :show_email, :boolean, default: false
# Show helpfullness rating form elements.
preference :feedback_rating, :boolean, default: false
# Require login to post reviews.
preference :require_login, :boolean, default: true
# Whether to keep track of the reviewer's locale.
preference :track_locale, :boolean, default: false
# Render checkbox for a user to approve to show their identifier
# (name or email) on their review.
preference :show_identifier, :boolean, default: false
# Control how many reviews are shown on the all reviews page.
preference :paginate_size, :integer, default: 10
def stars
5
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/overrides/add_reviews_after_product_properties.rb | app/overrides/add_reviews_after_product_properties.rb | Deface::Override.new(
virtual_path: 'spree/products/show',
name: 'converted_product_properties_767643482',
insert_after: '[data-hook="product_properties"]',
partial: 'spree/shared/reviews'
)
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/overrides/add_reviews_tab_to_admin.rb | app/overrides/add_reviews_tab_to_admin.rb | Deface::Override.new(
virtual_path: 'spree/admin/shared/sub_menu/_product',
name: 'reviews_admin_tab',
insert_bottom: '[data-hook="admin_product_sub_tabs"]',
text: '<%= tab(:reviews, label: "review_management") %>'
)
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/app/overrides/add_reviews_to_admin_configuration_sidebar.rb | app/overrides/add_reviews_to_admin_configuration_sidebar.rb | Deface::Override.new(
virtual_path: 'spree/admin/shared/sub_menu/_configuration',
name: 'converted_admin_configurations_menu',
insert_bottom: '[data-hook="admin_configurations_sidebar_menu"]',
text: '<%= configurations_sidebar_menu_item Spree.t(:review_settings, scope: :spree_reviews), edit_admin_review_settings_path %>'
)
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20140703200946_add_show_identifier_to_reviews.rb | db/migrate/20140703200946_add_show_identifier_to_reviews.rb | class AddShowIdentifierToReviews < SpreeExtension::Migration[4.2]
def change
add_column :spree_reviews, :show_identifier, :boolean, default: true
add_index :spree_reviews, :show_identifier
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20110806093221_add_ip_address_to_reviews.rb | db/migrate/20110806093221_add_ip_address_to_reviews.rb | class AddIpAddressToReviews < SpreeExtension::Migration[4.2]
def self.up
add_column :reviews, :ip_address, :string
end
def self.down
remove_column :reviews, :ip_address
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20120712182627_add_locale_to_feedback_reviews.rb | db/migrate/20120712182627_add_locale_to_feedback_reviews.rb | class AddLocaleToFeedbackReviews < SpreeExtension::Migration[4.2]
def self.up
add_column :spree_feedback_reviews, :locale, :string, default: 'en'
end
def self.down
remove_column :spree_feedback_reviews, :locale
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20110606150524_add_user_to_reviews.rb | db/migrate/20110606150524_add_user_to_reviews.rb | class AddUserToReviews < SpreeExtension::Migration[4.2]
def self.up
add_column :reviews, :user_id, :integer, null: true
end
def self.down
remove_column :reviews, :user_id
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20210728110707_change_user_id_and_review_id_type_for_spree_feedback_reviews.rb | db/migrate/20210728110707_change_user_id_and_review_id_type_for_spree_feedback_reviews.rb | class ChangeUserIdAndReviewIdTypeForSpreeFeedbackReviews < ActiveRecord::Migration[4.2]
def change
change_table(:spree_feedback_reviews) do |t|
t.change :user_id, :bigint
t.change :review_id, :bigint
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20110406083603_add_rating_to_products.rb | db/migrate/20110406083603_add_rating_to_products.rb | class AddRatingToProducts < SpreeExtension::Migration[4.2]
def self.up
if table_exists?('products')
add_column :products, :avg_rating, :decimal, default: 0.0, null: false, precision: 7, scale: 5
add_column :products, :reviews_count, :integer, default: 0, null: false
elsif table_exists?('spree_products')
add_column :spree_products, :avg_rating, :decimal, default: 0.0, null: false, precision: 7, scale: 5
add_column :spree_products, :reviews_count, :integer, default: 0, null: false
end
end
def self.down
if table_exists?('products')
remove_column :products, :reviews_count
remove_column :products, :avg_rating
elsif table_exists?('spree_products')
remove_column :spree_products, :reviews_count
remove_column :spree_products, :avg_rating
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20120712182514_add_locale_to_reviews.rb | db/migrate/20120712182514_add_locale_to_reviews.rb | class AddLocaleToReviews < SpreeExtension::Migration[4.2]
def self.up
add_column :spree_reviews, :locale, :string, default: 'en'
end
def self.down
remove_column :spree_reviews, :locale
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20210728110635_change_product_id_and_user_id_type_for_spree_reviews.rb | db/migrate/20210728110635_change_product_id_and_user_id_type_for_spree_reviews.rb | class ChangeProductIdAndUserIdTypeForSpreeReviews < ActiveRecord::Migration[4.2]
def change
change_table(:spree_reviews) do |t|
t.change :product_id, :bigint
t.change :user_id, :bigint
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20101222083309_create_feedback_reviews.rb | db/migrate/20101222083309_create_feedback_reviews.rb | class CreateFeedbackReviews < SpreeExtension::Migration[4.2]
def self.up
create_table :feedback_reviews do |t|
t.integer :user_id
t.integer :review_id, null: false
t.integer :rating, default: 0
t.text :comment
t.timestamps null: false
end
add_index :feedback_reviews, :review_id
add_index :feedback_reviews, :user_id
end
def self.down
drop_table :feedback_reviews
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20120110172331_namespace_tables.rb | db/migrate/20120110172331_namespace_tables.rb | class NamespaceTables < SpreeExtension::Migration[4.2]
def change
rename_table :reviews, :spree_reviews
rename_table :feedback_reviews, :spree_feedback_reviews
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20120123141326_recalculate_ratings.rb | db/migrate/20120123141326_recalculate_ratings.rb | class RecalculateRatings < SpreeExtension::Migration[4.2]
def up
Spree::Product.reset_column_information
Spree::Product.update_all reviews_count: 0
Spree::Product.joins(:reviews).where('spree_reviews.id IS NOT NULL').find_each do |p|
Spree::Product.update_counters p.id, reviews_count: p.reviews.approved.length
# recalculate_product_rating exists on the review, not the product
if p.reviews.approved.count > 0
p.reviews.approved.first.recalculate_product_rating
end
end
end
def down
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/db/migrate/20081020220724_create_reviews.rb | db/migrate/20081020220724_create_reviews.rb | class CreateReviews < SpreeExtension::Migration[4.2]
def self.up
create_table :reviews do |t|
t.integer :product_id
t.string :name
t.string :location
t.integer :rating
t.text :title
t.text :review
t.boolean :approved, default: false
t.timestamps null: false
end
end
def self.down
drop_table :reviews
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/spec_helper.rb | spec/spec_helper.rb | # Configure Rails Environment
ENV['RAILS_ENV'] = 'test'
require File.expand_path('dummy/config/environment.rb', __dir__)
require 'spree_dev_tools/rspec/spec_helper'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].sort.each { |f| require f }
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/helpers/review_helper_spec.rb | spec/helpers/review_helper_spec.rb | RSpec.describe Spree::ReviewsHelper, type: :helper do
context 'star' do
specify do
expect(star('a_class')).to eq '<span class="a_class"> ✮ </span>'
end
end
context 'mk_stars' do
specify do
matches = mk_stars(2).scan(/unlit/)
expect(matches.length).to be(3)
end
end
context 'txt_stars' do
specify do
expect(txt_stars(2, true)).to eq '2 out of 5'
end
specify do
expect(txt_stars(3, false)).to be_a String
expect(txt_stars(3, false)).to eq('3')
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/factories/feedback_review_factory.rb | spec/factories/feedback_review_factory.rb | FactoryBot.define do
factory :feedback_review, class: Spree::FeedbackReview do
user
review
comment { generate(:random_description) }
rating { rand(1..5) }
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/factories/review_factory.rb | spec/factories/review_factory.rb | FactoryBot.define do
factory :review, class: Spree::Review do
name { generate(:random_email) }
title { generate(:random_string) }
review { generate(:random_description) }
rating { rand(1..5) }
approved { false }
show_identifier { true }
user
product
trait :approved do
approved { true }
end
trait :hide_identifier do
show_identifier { false }
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/controllers/feedback_reviews_controller_spec.rb | spec/controllers/feedback_reviews_controller_spec.rb | RSpec.describe Spree::FeedbackReviewsController, type: :controller do
let(:user) { create(:user) }
let(:product) { create(:product) }
let(:review) { create(:review, user: user) }
before do
allow(controller).to receive(:spree_current_user).and_return(user)
allow(controller).to receive(:spree_user_signed_in?).and_return(true)
request.env['HTTP_REFERER'] = '/'
end
describe '#create' do
it 'creates a new feedback review' do
rating = 4
comment = generate(:random_description)
expect do
post(
:create,
params: {
review_id: review.id,
format: :js,
feedback_review: {
comment: comment,
rating: rating
}
}
)
expect(response.status).to be(200)
expect(response).to render_template(:create)
end.to change(Spree::Review, :count).by(1)
feedback_review = Spree::FeedbackReview.last
expect(feedback_review.comment).to eq(comment)
expect(feedback_review.review).to eq(review)
expect(feedback_review.rating).to eq(rating)
expect(feedback_review.user).to eq(user)
end
it 'redirects back to the calling page' do
post :create, params: {
review_id: review.id,
user_id: user.id,
feedback_review: { rating: '4 stars', comment: 'some comment' }
}
expect(response).to redirect_to('/')
end
it 'sets locale on feedback-review if required by config' do
Spree::Reviews::Config.preferred_track_locale = true
post :create, params: {
review_id: review.id,
user_id: user.id,
feedback_review: { rating: '4 stars', comment: 'some comment' }
}
expect(assigns[:review].locale).to eq I18n.locale.to_s
end
it 'fails when user is not authorized' do
allow(controller).to receive(:authorize!) { raise }
expect do
post :create, params: {
review_id: review.id,
user_id: user.id,
feedback_review: { rating: '4 stars', comment: 'some comment' }
}
end.to raise_error
end
it 'removes all non-numbers from ratings parameter' do
post :create, params: {
review_id: review.id,
user_id: user.id,
feedback_review: { rating: '4 stars', comment: 'some comment' }
}
expect(controller.params[:feedback_review][:rating]).to eq('4')
end
it 'does not create feedback-review if review doesnt exist' do
expect do
post :create, params: {
review_id: nil,
user_id: user.id,
feedback_review: { rating: '4 stars', comment: 'some comment' }
}
end.to raise_error
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/controllers/reviews_controller_spec.rb | spec/controllers/reviews_controller_spec.rb | RSpec.describe Spree::ReviewsController, type: :controller do
let(:user) { create(:user) }
let(:product) { create(:product) }
before do
allow(controller).to receive(:spree_current_user).and_return(user)
allow(controller).to receive(:spree_user_signed_in?).and_return(true)
end
describe '#index' do
context 'for a product that does not exist' do
it 'responds with a 404' do
expect { get :index, params: { product_id: 'not_real' } }.to raise_exception(ActiveRecord::RecordNotFound)
end
end
context 'for a valid product' do
it 'lists approved reviews' do
approved_reviews = [
create(:review, :approved, product: product),
create(:review, :approved, product: product)
]
get :index, params: { product_id: product.slug }
expect(assigns[:approved_reviews]).to match_array(approved_reviews)
end
end
end
describe '#new' do
context 'for a product that does not exist' do
it 'responds with a 404' do
expect { get :index, params: { product_id: 'not_real' } }.to raise_exception(ActiveRecord::RecordNotFound)
end
end
it 'fail if the user is not authorized to create a review' do
allow(controller).to receive(:authorize!) { raise }
expect do
post :new, params: { product_id: product.slug }
expect(response.body).to eq('ryanbig')
end.to raise_error
end
it 'renders the new template' do
get :new, params: { product_id: product.id }
expect(response.status).to be(200)
expect(response).to render_template(:new)
end
end
describe '#create' do
before do
allow(controller).to receive(:spree_current_user).and_return(user)
end
context 'for a product that does not exist' do
it 'responds with a 404' do
expect { post :create, params: { product_id: 'not_real' } }.to raise_exception(ActiveRecord::RecordNotFound)
end
end
it 'creates a new review' do
expect do
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
end.to change(Spree::Review, :count).by(1)
end
it 'sets the ip-address of the remote' do
allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return('127.0.0.1')
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
expect(assigns[:review].ip_address).to eq '127.0.0.1'
end
it 'fails if the user is not authorized to create a review' do
allow(controller).to receive(:authorize!) { raise }
expect do
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
end.to raise_error
end
it 'flashes the notice' do
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
expect(flash[:notice]).to eq Spree.t(:review_successfully_submitted)
end
it 'redirects to product page' do
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
expect(response).to redirect_to spree.product_path(product)
end
it 'removes all non-numbers from ratings param' do
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
expect(controller.params[:review][:rating]).to eq('3')
end
it 'sets the current spree user as reviews user' do
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
assigns[:review][:user_id] = user.id
expect(assigns[:review][:user_id]).to eq(user.id)
end
context 'with invalid params' do
it 'renders new when review.save fails' do
allow_any_instance_of(Spree::Review).to receive(:save).and_return(false)
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
expect(response).to render_template :new
end
it 'does not create a review' do
expect(Spree::Review.count).to be(0)
post :create, params: {
product_id: product,
review: { rating: 'not_a_number',
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' }
}
expect(Spree::Review.count).to be(0)
end
end
# It always sets the locale so preference pointless
context 'when config requires locale tracking:' do
it 'sets the locale' do
Spree::Reviews::Config.preferred_track_locale = true
post :create, params:
{ product_id: product,
review: { rating: 3,
name: 'Ryan Bigg',
title: 'Great Product',
review: 'Some big review text..' } }
expect(assigns[:review].locale).to eq I18n.locale.to_s
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/controllers/products_controller_spec.rb | spec/controllers/products_controller_spec.rb | RSpec.describe Spree::ProductsController, type: :controller do
reviews_fields = [:avg_rating, :reviews_count]
reviews_fields.each do |attrib|
it "adds #{attrib} to the set of allowed attributes" do
expect(controller.permitted_product_attributes).to include(attrib)
end
it "adds #{attrib} to the set of available attributes from Spree API" do
expect(Spree::PermittedAttributes.product_attributes).to include(attrib)
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/controllers/admin/feedback_reviews_controller_spec.rb | spec/controllers/admin/feedback_reviews_controller_spec.rb | RSpec.describe Spree::Admin::FeedbackReviewsController, type: :controller do
stub_authorization!
before do
user = create(:admin_user)
allow(controller).to receive(:try_spree_current_user).and_return(user)
end
context '#index' do
let!(:review) { create(:review) }
let!(:other_review) { create(:review) }
let!(:feedback_review_1) { create(:feedback_review, created_at: 10.days.ago, review: review) }
let!(:feedback_review_2) { create(:feedback_review, created_at: 2.days.ago, review: review) }
let!(:feedback_review_3) { create(:feedback_review, created_at: 5.days.ago, review: review) }
let!(:other_feedback_review_1) { create(:feedback_review, created_at: 10.days.ago, review: other_review) }
let!(:other_feedback_review_2) { create(:feedback_review, created_at: 2.days.ago, review: other_review) }
it 'looks up feedback reviews for the specified review and renders the template' do
get :index, params: { review_id: review.id }
expect(response.status).to be(200)
expect(response).to render_template(:index)
expect(assigns(:collection)).to match_array [feedback_review_2, feedback_review_3, feedback_review_1]
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/controllers/admin/review_settings_controller_spec.rb | spec/controllers/admin/review_settings_controller_spec.rb | RSpec.describe Spree::Admin::ReviewSettingsController, type: :controller do
stub_authorization!
before do
reset_spree_preferences
user = create(:admin_user)
allow(controller).to receive(:try_spree_current_user).and_return(user)
end
describe '#update' do
it 'redirects to review settings page' do
put :update, params: { preferences: { preview_size: 4 } }
expect(response).to redirect_to spree.edit_admin_review_settings_path
end
context 'For parameters:
include_unapproved_reviews: true
preview_size: 4,
show_email: true,
feedback_rating: true,
require_login: false,
track_locale: true
show_identifier: true' do
subject { Spree::Reviews::Config }
it 'sets preferred_include_unapproved_reviews to false' do
put :update, params: { preferences: { include_unapproved_reviews: true } }
expect(subject.preferred_include_unapproved_reviews).to be(true)
end
it 'sets preferred_preview_size to 4' do
put :update, params: { preferences: { preview_size: 4 } }
expect(subject.preferred_preview_size).to be(4)
end
it 'sets preferred_show_email to false' do
put :update, params: { preferences: { show_email: true } }
expect(subject.preferred_show_email).to be(true)
end
it 'sets preferred_feedback_rating to false' do
put :update, params: { preferences: { feedback_rating: true } }
expect(subject.preferred_feedback_rating).to be(true)
end
it 'sets preferred_require_login to true' do
put :update, params: { preferences: { require_login: false } }
expect(subject.preferred_require_login).to be(false)
end
it 'sets preferred_track_locale to true' do
put :update, params: { preferences: { track_locale: true } }
expect(subject.preferred_track_locale).to be(true)
end
it 'sets preferred_show_identifier to false' do
put :update, params: { preferences: { show_identifier: true } }
expect(subject.preferred_show_identifier).to be(true)
end
end
end
describe '#edit' do
it 'renders the edit template' do
get :edit
expect(response).to render_template(:edit)
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/controllers/admin/reviews_controller_spec.rb | spec/controllers/admin/reviews_controller_spec.rb | RSpec.describe Spree::Admin::ReviewsController, type: :controller do
stub_authorization!
let(:product) { create(:product) }
let(:review) { create(:review, approved: false) }
before do
user = create(:admin_user)
allow(controller).to receive(:try_spree_current_user).and_return(user)
end
describe '#index' do
it 'lists reviews' do
reviews = [
create(:review),
create(:review)
]
get :index, params: { product_id: product.slug }
expect(assigns[:reviews]).to match_array(reviews)
end
end
describe '#approve' do
it 'shows notice message when approved' do
review.update_attribute(:approved, true)
get :approve, params: { id: review.id }
expect(response).to redirect_to spree.admin_reviews_path
expect(flash[:notice]).to eq Spree.t(:info_approve_review)
end
it 'shows error message when not approved' do
allow_any_instance_of(Spree::Review).to receive(:update_attribute).and_return(false)
get :approve, params: { id: review.id }
expect(flash[:error]).to eq Spree.t(:error_approve_review)
end
end
describe '#edit' do
it 'returns http success' do
get :edit, params: { id: review.id }
expect(response.status).to be(200)
end
context 'when product is nil' do
before do
review.update_attribute(:product_id, nil)
review.save
end
it 'flashes error' do
get :edit, params: { id: review.id }
expect(flash[:error]).to eq Spree.t(:error_no_product)
end
it 'redirects to admin-reviews page' do
get :edit, params: { id: review.id }
expect(response).to redirect_to spree.admin_reviews_path
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/models/feedback_review_spec.rb | spec/models/feedback_review_spec.rb | RSpec.describe Spree::FeedbackReview, type: :model do
context 'validations' do
it 'validates by default' do
expect(build(:feedback_review)).to be_valid
end
it 'validates with a nil user' do
expect(build(:feedback_review, user: nil)).not_to be_valid
end
it 'does not validate with a nil review' do
expect(build(:feedback_review, review: nil)).not_to be_valid
end
context 'rating' do
it 'does not validate when no rating is specified' do
expect(build(:feedback_review, rating: nil)).not_to be_valid
end
it 'does not validate when the rating is not a number' do
expect(build(:feedback_review, rating: 'not_a_number')).not_to be_valid
end
it 'does not validate when the rating is a float' do
expect(build(:feedback_review, rating: 2.718)).not_to be_valid
end
it 'does not validate when the rating is less than 1' do
expect(build(:feedback_review, rating: 0)).not_to be_valid
expect(build(:feedback_review, rating: -5)).not_to be_valid
end
it 'does not validate when the rating is greater than 5' do
expect(build(:feedback_review, rating: 6)).not_to be_valid
expect(build(:feedback_review, rating: 8)).not_to be_valid
end
(1..5).each do |i|
it "validates when the rating is #{i}" do
expect(build(:feedback_review, rating: i)).to be_valid
end
end
end
end
context 'scopes' do
context 'most_recent_first' do
let!(:feedback_review_1) { create(:feedback_review, created_at: 10.days.ago) }
let!(:feedback_review_2) { create(:feedback_review, created_at: 2.days.ago) }
let!(:feedback_review_3) { create(:feedback_review, created_at: 5.days.ago) }
it 'properly runs most_recent_first queries' do
expected = [feedback_review_2, feedback_review_3, feedback_review_1]
expect(described_class.most_recent_first.to_a).to match_array expected
end
it 'defaults to most_recent_first queries' do
expected = [feedback_review_2, feedback_review_3, feedback_review_1]
expect(described_class.all.to_a).to match_array expected
end
end
context 'localized' do
let!(:en_feedback_review_1) { create(:feedback_review, locale: 'en', created_at: 10.days.ago) }
let!(:en_feedback_review_2) { create(:feedback_review, locale: 'en', created_at: 2.days.ago) }
let!(:en_feedback_review_3) { create(:feedback_review, locale: 'en', created_at: 5.days.ago) }
let!(:es_feedback_review_1) { create(:feedback_review, locale: 'es', created_at: 10.days.ago) }
let!(:fr_feedback_review_1) { create(:feedback_review, locale: 'fr', created_at: 10.days.ago) }
it 'properly runs localized queries' do
expected_en = [en_feedback_review_2, en_feedback_review_3, en_feedback_review_1]
expect(described_class.localized('en').to_a).to match_array expected_en
expect(described_class.localized('es').to_a).to match_array [es_feedback_review_1]
expect(described_class.localized('fr').to_a).to match_array [fr_feedback_review_1]
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/models/review_spec.rb | spec/models/review_spec.rb | RSpec.describe Spree::Review, type: :model do
context 'validations' do
it 'validates by default' do
expect(build(:review)).to be_valid
end
it 'does not validate with a nil review' do
expect(build(:review, review: nil)).not_to be_valid
end
context 'rating' do
it 'does not validate when no rating is specified' do
expect(build(:review, rating: nil)).not_to be_valid
end
it 'does not validate when the rating is not a number' do
expect(build(:review, rating: 'not_a_number')).not_to be_valid
end
it 'does not validate when the rating is a float' do
expect(build(:review, rating: 2.718)).not_to be_valid
end
it 'does not validate when the rating is less than 1' do
expect(build(:review, rating: 0)).not_to be_valid
expect(build(:review, rating: -5)).not_to be_valid
end
it 'does not validate when the rating is greater than 5' do
expect(build(:review, rating: 6)).not_to be_valid
expect(build(:review, rating: 8)).not_to be_valid
end
(1..5).each do |i|
it "validates when the rating is #{i}" do
expect(build(:review, rating: i)).to be_valid
end
end
end
context 'review body' do
it 'is not be valid without a body' do
expect(build(:review, review: nil)).not_to be_valid
end
end
end
context 'scopes' do
context 'most_recent_first' do
let!(:review_1) { create(:review, created_at: 10.days.ago) }
let!(:review_2) { create(:review, created_at: 2.days.ago) }
let!(:review_3) { create(:review, created_at: 5.days.ago) }
it 'properly runs most_recent_first queries' do
expect(described_class.most_recent_first.to_a).to eq([review_2, review_3, review_1])
end
it 'defaults to most_recent_first queries' do
expect(described_class.all.to_a).to eq([review_2, review_3, review_1])
end
end
context 'oldest_first' do
let!(:review_1) { create(:review, created_at: 10.days.ago) }
let!(:review_2) { create(:review, created_at: 2.days.ago) }
let!(:review_3) { create(:review, created_at: 5.days.ago) }
let!(:review_4) { create(:review, created_at: 1.days.ago) }
before do
reset_spree_preferences
end
it 'properly runs oldest_first queries' do
expect(described_class.oldest_first.to_a).to eq([review_1, review_3, review_2, review_4])
end
it 'uses oldest_first for preview' do
reset_spree_preferences
expect(described_class.preview.to_a).to eq([review_1, review_3, review_2])
end
end
context 'localized' do
let!(:en_review_1) { create(:review, locale: 'en', created_at: 10.days.ago) }
let!(:en_review_2) { create(:review, locale: 'en', created_at: 2.days.ago) }
let!(:en_review_3) { create(:review, locale: 'en', created_at: 5.days.ago) }
let!(:es_review_1) { create(:review, locale: 'es', created_at: 10.days.ago) }
let!(:fr_review_1) { create(:review, locale: 'fr', created_at: 10.days.ago) }
it 'properly runs localized queries' do
expect(described_class.localized('en').to_a).to eq([en_review_2, en_review_3, en_review_1])
expect(described_class.localized('es').to_a).to eq([es_review_1])
expect(described_class.localized('fr').to_a).to eq([fr_review_1])
end
end
context 'approved / not_approved / default_approval_filter' do
let!(:approved_review_1) { create(:review, approved: true, created_at: 10.days.ago) }
let!(:approved_review_2) { create(:review, approved: true, created_at: 2.days.ago) }
let!(:approved_review_3) { create(:review, approved: true, created_at: 5.days.ago) }
let!(:unapproved_review_1) { create(:review, approved: false, created_at: 7.days.ago) }
let!(:unapproved_review_2) { create(:review, approved: false, created_at: 1.days.ago) }
it 'properly runs approved and unapproved queries' do
expected = [
approved_review_2,
approved_review_3,
approved_review_1
]
expect(described_class.approved.to_a).to match_array expected
expected = [
unapproved_review_2,
unapproved_review_1
]
expect(described_class.not_approved.to_a).to match_array expected
Spree::Reviews::Config[:include_unapproved_reviews] = true
expected = [
unapproved_review_2,
approved_review_2,
approved_review_3,
unapproved_review_1,
approved_review_1
]
expect(described_class.default_approval_filter.to_a).to match_array expected
Spree::Reviews::Config[:include_unapproved_reviews] = false
expected = [
approved_review_2,
approved_review_3,
approved_review_1
]
expect(Spree::Review.default_approval_filter.to_a).to match_array expected
end
end
end
describe '.recalculate_product_rating' do
let(:product) { create(:product) }
let!(:review) { create(:review, product: product) }
before { product.reviews << review }
it 'if approved' do
expect(review).to receive(:recalculate_product_rating)
review.approved = true
review.save!
end
it 'if not approved' do
expect(review).not_to receive(:recalculate_product_rating)
review.save!
end
it 'updates the product average rating' do
expect(review.product).to receive(:recalculate_rating)
review.approved = true
review.save!
end
end
describe '.feedback_stars' do
let!(:user) { create(:user) }
let!(:review) { create(:review) }
before do
3.times do |i|
f = Spree::FeedbackReview.new
f.user = user
f.review = review
f.rating = (i + 1)
f.save!
end
end
it 'returns the average rating from feedback reviews' do
expect(review.feedback_stars).to be(2)
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/models/reviews_ability_spec.rb | spec/models/reviews_ability_spec.rb | require 'cancan/matchers'
RSpec.describe Spree::ReviewsAbility, type: :model do
describe '.allow_anonymous_reviews?' do
it 'depends on Spree::Reviews::Config[:require_login]' do
Spree::Reviews::Config[:require_login] = false
expect(described_class.allow_anonymous_reviews?).to be(true)
Spree::Reviews::Config[:require_login] = true
expect(described_class.allow_anonymous_reviews?).to be(false)
end
end
context 'permissions' do
let(:user_without_email) { double(:user, email: nil) }
let(:user_with_email) { double(:user, email: 'a@b.com') }
context 'when anonymous reviews are allowed' do
before do
Spree::Reviews::Config[:require_login] = false
end
it 'lets anyone create a review or feedback review' do
[user_without_email, user_with_email].each do |u|
expect(described_class.new(u)).to be_able_to(:create, Spree::Review.new)
expect(described_class.new(u)).to be_able_to(:create, Spree::FeedbackReview.new)
end
end
end
context 'when anonymous reviews are not allowed' do
before do
Spree::Reviews::Config[:require_login] = true
end
it 'only allows users with an email to create a review or feedback review' do
expect(described_class.new(user_without_email)).not_to be_able_to(:create, Spree::Review.new)
expect(described_class.new(user_without_email)).not_to be_able_to(:create, Spree::FeedbackReview.new)
expect(described_class.new(user_with_email)).to be_able_to(:create, Spree::Review.new)
expect(described_class.new(user_with_email)).to be_able_to(:create, Spree::FeedbackReview.new)
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/models/product_spec.rb | spec/models/product_spec.rb | RSpec.describe Spree::Product, type: :model do
it { is_expected.to respond_to(:avg_rating) }
it { is_expected.to respond_to(:reviews) }
it { is_expected.to respond_to(:stars) }
describe '.stars' do
let(:product) { build(:product) }
it 'rounds' do
allow(product).to receive(:avg_rating).and_return(3.7)
expect(product.stars).to be(4)
allow(product).to receive(:avg_rating).and_return(2.3)
expect(product.stars).to be(2)
end
it 'handles a nil value' do
allow(product).to receive(:avg_rating).and_return(nil)
expect {
expect(product.stars).to be(0)
}.not_to raise_error
end
end
describe '.recalculate_rating' do
let!(:product) { create(:product) }
context 'when there are approved reviews' do
let!(:approved_review_1) { create(:review, product: product, approved: true, rating: 4) }
let!(:approved_review_2) { create(:review, product: product, approved: true, rating: 5) }
let!(:unapproved_review_1) { create(:review, product: product, approved: false, rating: 4) }
it 'updates the product average rating and ignores unapproved reviews' do
product.avg_rating = 0
product.reviews_count = 0
product.save!
product.recalculate_rating
expect(product.avg_rating.to_f).to be(4.5)
expect(product.reviews_count).to be(2)
end
end
context 'when no approved reviews' do
let!(:unapproved_review_1) { create(:review, product: product, approved: false, rating: 4) }
it 'updates the product average rating and ignores unapproved reviews' do
product.avg_rating = 3
product.reviews_count = 20
product.save!
product.recalculate_rating
expect(product.avg_rating.to_f).to be(0.0)
expect(product.reviews_count).to be(0)
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/models/spree_reviews/configuration_spec.rb | spec/models/spree_reviews/configuration_spec.rb | RSpec.describe Spree::ReviewSetting do
subject { described_class.new }
before do
reset_spree_preferences
end
it 'have the include_unapproved_reviews preference' do
expect(subject).to respond_to(:preferred_include_unapproved_reviews)
expect(subject).to respond_to(:preferred_include_unapproved_reviews=)
expect(subject.preferred_include_unapproved_reviews).to be(false)
end
it 'have the preview_size preference' do
expect(subject).to respond_to(:preferred_preview_size)
expect(subject).to respond_to(:preferred_preview_size=)
expect(subject.preferred_preview_size).to be(3)
end
it 'have the show_email preference' do
expect(subject).to respond_to(:preferred_show_email)
expect(subject).to respond_to(:preferred_show_email=)
expect(subject.preferred_show_email).to be(false)
end
it 'have the feedback_rating preference' do
expect(subject).to respond_to(:preferred_feedback_rating)
expect(subject).to respond_to(:preferred_feedback_rating=)
expect(subject.preferred_feedback_rating).to be(false)
end
it 'have the require_login preference' do
expect(subject).to respond_to(:preferred_require_login)
expect(subject).to respond_to(:preferred_require_login=)
expect(subject.preferred_require_login).to be(true)
end
it 'have the track_locale preference' do
expect(subject).to respond_to(:preferred_track_locale)
expect(subject).to respond_to(:preferred_track_locale=)
expect(subject.preferred_track_locale).to be(false)
end
it 'have the show_identifier preference' do
expect(subject).to respond_to(:preferred_show_identifier)
expect(subject).to respond_to(:preferred_show_identifier=)
expect(subject.preferred_show_identifier).to be(false)
end
describe '.stars' do
it 'returns Integer' do
expect(subject.stars).to be_a Integer
expect(subject.stars).to be(5)
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/features/reviews_spec.rb | spec/features/reviews_spec.rb | describe 'Reviews', :js do
let!(:someone) { create(:user, email: 'admin1@person.com', password: 'password', password_confirmation: 'password') }
let!(:review) { create(:review, :approved, user: someone) }
before do
Spree::Reviews::Config.include_unapproved_reviews = false
end
context 'product with no review' do
let!(:product_no_reviews) { create(:product) }
it 'informs that no reviews has been written yet' do
visit spree.product_path(product_no_reviews)
expect(page).to have_text Spree.t(:no_reviews_available)
end
# Regression test for #103
context 'shows correct number of previews' do
before do
create_list :review, 3, product: product_no_reviews, approved: true
Spree::Reviews::Config[:preview_size] = 2
end
it 'displayed reviews are limited by the set preview size' do
visit spree.product_path(product_no_reviews)
expect(page.all('.review').count).to be(2)
end
end
end
context 'when anonymous user' do
before do
Spree::Reviews::Config.require_login = true
end
context 'visit product with review' do
before do
visit spree.product_path(review.product)
end
it 'can see review title' do
expect(page).to have_text review.title
end
it 'can see a prompt to review' do
expect(page).to have_text Spree.t(:write_your_own_review)
end
end
end
context 'when logged in user' do
context 'visit product with review' do
before do
Spree::Reviews::Config.require_login = true
visit spree.product_path(review.product)
end
it 'can see review title' do
expect(page).to have_text review.title
end
it 'can see create new review button' do
expect(page).to have_text Spree.t(:write_your_own_review)
end
it 'can create new review' do
user = create(:user, email: 'admin4546@person.com', password: 'password', password_confirmation: 'password')
click_on Spree.t(:write_your_own_review)
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
if Spree.version.to_f > 4.0 && Spree.version.to_f < 4.2
click_button 'Log in'
else
click_button 'Login'
end
expect(page).to have_text Spree.t(:leave_us_a_review_for, name: review.product.name)
expect(page).not_to have_text 'Show Identifier'
within '#new_review' do
click_star(3)
fill_in 'review_name', with: someone.email
fill_in 'review_title', with: 'Great product!'
fill_in 'review_review', with: 'Some big review text..'
click_on 'Submit your review'
end
expect(page).to have_text Spree.t(:review_successfully_submitted)
expect(page).not_to have_text 'Some big review text..'
end
end
end
context 'visits product with review where show_identifier is false' do
let!(:review) { create(:review, :approved, :hide_identifier, review: 'review text', user: someone) }
before do
visit spree.product_path(review.product)
end
it 'show anonymous review' do
expect(page).to have_text Spree.t(:anonymous)
expect(page).to have_text 'review text'
end
end
private
def click_star(num)
page.all(:xpath, "//a[@title='#{num} stars']")[0].click
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/features/admin_spec.rb | spec/features/admin_spec.rb | require 'spec_helper'
describe 'Review Admin', :js do
stub_authorization!
let!(:review) { create(:review) }
context 'index' do
before do
visit spree.admin_reviews_path
end
it 'list reviews' do
expect(page).to have_content(review.product.name)
end
it 'approve reviews' do
expect(review.approved).to be(false)
within("tr#review_#{review.id}") do
find('.approve').click
end
expect(review.reload.approved).to be(true)
end
it 'edit reviews' do
expect(page).to have_text review.product.name
within("tr#review_#{review.id}") do
click_icon :edit
end
expect(page).to have_content('Editing')
expect(page).to have_content(review.title)
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/spec/features/admin/review_setting_spec.rb | spec/features/admin/review_setting_spec.rb | require 'spec_helper'
describe 'Admin Settings for Reviews', :js do
stub_authorization!
before do
visit spree.edit_admin_review_settings_path
end
it 'update' do
the_key_string = Spree.t(:preview_size, scope: :spree_reviews)
if Spree.version.to_f < 4.0
expect(page).to have_content(the_key_string.upcase)
else
expect(page).to have_content(the_key_string)
end
check 'include_unapproved_reviews'
check 'feedback_rating'
check 'show_email'
check 'require_login'
check 'track_locale'
check 'show_identifier'
fill_in 'preview_size', with: '5'
fill_in 'paginate_size', with: '6'
click_button 'Update'
expect(page).to have_content('successfully updated!')
setting = Spree::ReviewSetting.new
expect(setting.preferred_include_unapproved_reviews).to be(true)
expect(setting.preferred_feedback_rating).to be(true)
expect(setting.preferred_show_email).to be(true)
expect(setting.preferred_require_login).to be(true)
expect(setting.preferred_track_locale).to be(true)
expect(setting.preferred_show_identifier).to be(true)
expect(setting.preferred_preview_size).to be(5)
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/lib/spree_reviews.rb | lib/spree_reviews.rb | require 'spree_core'
require 'spree_extension'
require 'spree_backend'
require 'spree_reviews/engine'
require 'spree_reviews/version'
require 'deface'
require 'sass/rails'
module Spree
module Reviews
module_function
def config(*)
yield(Spree::Reviews::Config)
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/lib/generators/spree_reviews/install/install_generator.rb | lib/generators/spree_reviews/install/install_generator.rb | module SpreeReviews
module Generators
class InstallGenerator < Rails::Generators::Base
class_option :auto_run_migrations, type: :boolean, default: false
def add_javascripts
append_file 'vendor/assets/javascripts/spree/frontend/all.js', "//= require spree/frontend/spree_reviews\n"
append_file 'vendor/assets/javascripts/spree/backend/all.js', "//= require spree/backend/spree_reviews\n"
end
def add_stylesheets
inject_into_file 'vendor/assets/stylesheets/spree/frontend/all.css', " *= require spree/frontend/spree_reviews\n", before: %r{\*/}, verbose: true
end
def add_migrations
run 'bundle exec rake railties:install:migrations FROM=spree_reviews'
end
def run_migrations
run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]')
if run_migrations
run 'bundle exec rake db:migrate'
else
puts 'Skipping rake db:migrate, don\'t forget to run it!'
end
end
end
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/lib/spree_reviews/version.rb | lib/spree_reviews/version.rb | module SpreeReviews
module_function
# Returns the version of the currently loaded SpreeReviews as a
# <tt>Gem::Version</tt>.
def version
Gem::Version.new VERSION::STRING
end
module VERSION
MAJOR = 4
MINOR = 0
TINY = 0
STRING = [MAJOR, MINOR, TINY].compact.join('.')
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/lib/spree_reviews/engine.rb | lib/spree_reviews/engine.rb | module SpreeReviews
class Engine < Rails::Engine
require 'spree/core'
isolate_namespace Spree
engine_name 'spree_reviews'
config.autoload_paths += %W[#{config.root}/lib]
# use rspec for tests
config.generators do |g|
g.test_framework :rspec
end
initializer 'spree_reviews.environment', before: :load_config_initializers do |_app|
Config = Configuration.new
end
config.after_initialize do
Spree::Reviews::Config = Spree::ReviewSetting.new
end
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c|
Rails.configuration.cache_classes ? require(c) : load(c)
end
Spree::Ability.register_ability(Spree::ReviewsAbility)
end
config.to_prepare(&method(:activate).to_proc)
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/config/routes.rb | config/routes.rb | Spree::Core::Engine.add_routes do
namespace :admin do
resources :reviews, only: [:index, :destroy, :edit, :update] do
member do
get :approve
end
resources :feedback_reviews, only: [:index, :destroy]
end
resource :review_settings, only: [:edit, :update]
end
resources :products, only: [] do
resources :reviews, only: [:index, :new, :create] do
end
end
post '/reviews/:review_id/feedback(.:format)' => 'feedback_reviews#create', as: :feedback_reviews
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/config/initializers/spree_permitted_attributes.rb | config/initializers/spree_permitted_attributes.rb | module Spree
module PermittedAttributes
ATTRIBUTES += %i[review_attributes feedback_review_attributes]
mattr_reader *ATTRIBUTES
@@product_attributes += %i[avg_rating reviews_count]
@@review_attributes = [:rating, :title, :review, :name, :show_identifier]
@@feedback_review_attributes = [:rating, :comment]
end
end
| ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
spree-contrib/spree_reviews | https://github.com/spree-contrib/spree_reviews/blob/36ef2809191c79729b93e00518aa74bf9c93b6c4/config/initializers/asset.rb | config/initializers/asset.rb | Rails.application.config.assets.precompile << 'spree_reviews_manifest.js' | ruby | BSD-3-Clause | 36ef2809191c79729b93e00518aa74bf9c93b6c4 | 2026-01-04T17:52:25.076508Z | false |
defunkt/nginx_config_generator | https://github.com/defunkt/nginx_config_generator/blob/183d858c4f93aeafd11f543119c8e8cf20c9dc93/lib/nginx_config_generator.rb | lib/nginx_config_generator.rb | #! /usr/bin/env ruby
%w(erb yaml).each &method(:require)
def error(message) puts(message) || exit end
def file(file) "#{File.dirname(__FILE__)}/#{file}" end
if ARGV.include? '--example'
example = file:'config.yml.example'
error open(example).read
end
env_in = ENV['NGINX_CONFIG_YAML']
env_out = ENV['NGINX_CONFIG_FILE']
error "Usage: generate_nginx_config [config file] [out file]" if ARGV.empty? && !env_in
overwrite = %w(-y -o -f --force --overwrite).any? { |f| ARGV.delete(f) }
config = YAML.load(ERB.new(File.read(env_in || ARGV.shift || 'config.yml')).result)
template = if custom_template_index = (ARGV.index('--template') || ARGV.index('-t'))
custom = ARGV[custom_template_index+1]
error "=> Specified template file #{custom} does not exist." unless File.exist?(custom)
ARGV.delete_at(custom_template_index) # delete the --argument
ARGV.delete_at(custom_template_index) # and its value
custom
else
file:'nginx.erb'
end
if File.exists?(out_file = env_out || ARGV.shift || 'nginx.conf') && !overwrite
error "=> #{out_file} already exists, won't overwrite it. Quitting."
else
open(out_file, 'w+').write(ERB.new(File.read(template), nil, '>').result(binding))
error "=> Wrote #{out_file} successfully."
end
| ruby | MIT | 183d858c4f93aeafd11f543119c8e8cf20c9dc93 | 2026-01-04T17:52:38.646762Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/spec/underlock_spec.rb | spec/underlock_spec.rb | require "spec_helper"
describe Underlock do
it "has a version number" do
expect(Underlock::VERSION).not_to be nil
end
end
| ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/spec/spec_helper.rb | spec/spec_helper.rb | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "underlock"
require "yomu"
require "pry"
RSpec.configure do |config|
Underlock::Base.configure do |config|
config.public_key = File.read('./spec/key.pub')
config.private_key = File.read('./spec/key.priv')
config.cipher = OpenSSL::Cipher.new('aes-256-gcm')
end
config.after(:suite) do
FileUtils.rm Dir.glob('./spec/files/*.decrypted.txt')
FileUtils.rm Dir.glob('./spec/files/*.enc')
end
end | ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/spec/underlock/base_spec.rb | spec/underlock/base_spec.rb | require 'spec_helper'
describe Underlock::Base do
it 'should implement #encrypt & #decrypt' do
expect(described_class).to respond_to(:encrypt)
expect(described_class).to respond_to(:decrypt)
end
context 'string encryption' do
let(:secret) { Underlock::Base.encrypt(message) }
context 'encrypt' do
let(:message) { 'secret message: unicorns' }
it 'should return an instance of EncryptedEntity' do
expect(secret).to be_an_instance_of(Underlock::EncryptedEntity)
end
it 'should not have the original value' do
expect(secret.value).to_not eq(message)
end
it 'should be able to decrypt the gibberish back to the actual message' do
expect(Underlock::Base.decrypt(secret)).to eq(message)
end
end
context 'decrypt' do
let(:message) { 'super secret message to get across' }
it 'should be able to decrypt the gibberish back to the actual message' do
expect(Underlock::Base.decrypt(secret)).to eq(message)
end
context 'multiline strings' do
let(:message) do
message = <<-SECRET_MESSAGE
This here is a
multiline string,
and also a super secret message
that should be protected
SECRET_MESSAGE
end
it 'should be able to decrypt the gibberish back to the actual message' do
expect(Underlock::Base.decrypt(secret)).to eq(message)
end
end
end
context 'when passing a string that is a valid path' do
let(:message) { './spec/files/file.txt' }
it 'should be able to decrypt the gibberish back to the actual path' do
expect(Underlock::Base.decrypt(secret)).to eq(message)
end
end
end
context 'file encryption' do
let(:secret) { Underlock::Base.encrypt(file) }
%w(file.pdf file.txt).each do |filename|
%w(file pathname).each do |elem|
if elem == 'file'
let(:file) { File.open("./spec/files/#{filename}") }
else
let(:file) { Pathname.new("./spec/files/#{filename}") }
end
context 'encrypt' do
it 'should return an instance of EncryptedEntity' do
expect(secret).to be_an_instance_of(Underlock::EncryptedEntity)
end
it 'should respond to #encrypted_file' do
expect(secret).to respond_to(:encrypted_file)
end
it 'should not have the original value' do
expect(File.read(secret.encrypted_file)).to_not eq(File.read(file))
end
end
context 'decrypt' do
let(:encrypted_entity) { Underlock::Base.encrypt(file) }
it 'should be able to return a file for an encrypted file' do
expect(Underlock::Base.decrypt(encrypted_entity)).to be_an_instance_of(File)
end
it 'should be able to read the contents of the file' do
decrypted_file = Underlock::Base.decrypt(encrypted_entity)
yomu = Yomu.new(decrypted_file.to_path)
expect(yomu.text.strip).to eq("super secret message in the pdf file")
end
end
end
end
end
end | ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/lib/underlock.rb | lib/underlock.rb | require 'underlock/version'
require 'dry-configurable'
require 'openssl'
require 'underlock/encryptor'
require 'underlock/file_encryptor'
require 'underlock/encrypted_entity'
require 'underlock/base'
module Underlock
end
| ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/lib/underlock/version.rb | lib/underlock/version.rb | module Underlock
VERSION = "0.0.5"
end
| ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/lib/underlock/file_encryptor.rb | lib/underlock/file_encryptor.rb | module Underlock
class FileEncryptor
def encrypt(file)
file = File.realpath(file)
@base_dir, @filename = File.split(file)
cipher = Underlock::Base.config.cipher.dup
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
File.open(encrypted_filepath, "wb") do |encrypted_file|
File.open(file, 'rb') do |inf|
loop do
r = inf.read(4096)
break unless r
encrypted_file << cipher.update(r)
end
end
encrypted_file << cipher.final
end
encrypted_file = File.new(encrypted_filepath)
encrypted_key = public_encrypt(key)
encrypted_iv = public_encrypt(iv)
EncryptedEntity.new(encrypted_file: encrypted_file, key: encrypted_key, iv: encrypted_iv)
end
def decrypt(encrypted_entity)
decode_cipher = Underlock::Base.config.cipher.dup
decode_cipher.decrypt
decode_cipher.key = private_decrypt(encrypted_entity.key)
decode_cipher.iv = private_decrypt(encrypted_entity.iv)
@base_dir, @filename = File.split(encrypted_entity.encrypted_file)
File.open(decrypted_filepath, 'wb') do |decrypted_file|
File.open(encrypted_entity.encrypted_file, 'rb') do |inf|
loop do
r = inf.read(4096)
break unless r
decrypted_file << decode_cipher.update(r)
end
end
end
File.new(decrypted_filepath)
end
private
def encrypted_filepath
"#{@base_dir}/#{@filename}.enc"
end
def decrypted_filepath
original_filename = @filename.gsub('.enc', '')
extension = File.extname(original_filename)
decrypted_filename = original_filename.gsub(extension, ".decrypted#{extension}")
"#{@base_dir}/#{decrypted_filename}"
end
def public_encrypt(value)
key = OpenSSL::PKey::RSA.new(Underlock::Base.config.public_key)
base64_encode(key.public_encrypt(base64_encode(value)))
end
def private_decrypt(value)
key = OpenSSL::PKey::RSA.new(Underlock::Base.config.private_key)
base64_decode(key.private_decrypt(base64_decode(value)[0]))[0]
end
def base64_encode(value)
[value].pack('m')
end
def base64_decode(value)
value.unpack('m')
end
end
end | ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/lib/underlock/encryptor.rb | lib/underlock/encryptor.rb | module Underlock
class Encryptor
def encrypt(value)
cipher = Underlock::Base.config.cipher.dup
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
encrypted_value = base64_encode(cipher.update(value))
encrypted_key = public_encrypt(key)
encrypted_iv = public_encrypt(iv)
EncryptedEntity.new(value: encrypted_value, key: encrypted_key, iv: encrypted_iv)
end
def decrypt(encrypted_entity)
decode_cipher = Underlock::Base.config.cipher.dup
decode_cipher.decrypt
decode_cipher.key = private_decrypt(encrypted_entity.key)
decode_cipher.iv = private_decrypt(encrypted_entity.iv)
decode_cipher.update(base64_decode(encrypted_entity.value)[0])
end
private
def public_encrypt(value)
key = OpenSSL::PKey::RSA.new(Underlock::Base.config.public_key)
base64_encode(key.public_encrypt(base64_encode(value)))
end
def private_decrypt(value)
key = OpenSSL::PKey::RSA.new(Underlock::Base.config.private_key)
base64_decode(key.private_decrypt(base64_decode(value)[0]))[0]
end
def base64_encode(value)
[value].pack('m')
end
def base64_decode(value)
value.unpack('m')
end
end
end | ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/lib/underlock/encrypted_entity.rb | lib/underlock/encrypted_entity.rb | module Underlock
class EncryptedEntity
attr_accessor :value, :encrypted_file, :key, :iv
def initialize(value: nil, encrypted_file: nil, key:, iv:)
@encrypted_file = encrypted_file
@value = value
@key = key
@iv = iv
end
def decrypt
return Encryptor.new.decrypt(self) if value
return FileEncryptor.new.decrypt(self) if encrypted_file
end
def inspect
self.to_s
end
end
end | ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
metaware/underlock | https://github.com/metaware/underlock/blob/4f020f9de1229a41009b4b83ae3b7778a7cb2629/lib/underlock/base.rb | lib/underlock/base.rb | module Underlock
class Base
extend Dry::Configurable
setting :private_key
setting :public_key
setting :passphrase
setting :cipher
class << self
def encrypt(unencrypted_value)
case unencrypted_value
when File, Pathname then FileEncryptor.new.encrypt(unencrypted_value)
when String then Encryptor.new.encrypt(unencrypted_value)
end
end
def decrypt(encrypted_entity)
encrypted_entity.decrypt
end
end
end
end | ruby | MIT | 4f020f9de1229a41009b4b83ae3b7778a7cb2629 | 2026-01-04T17:52:39.666784Z | false |
mttkay/replicant | https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/helper.rb | test/helper.rb | begin
Bundler.require(:default, :test)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
# additional test modules
require 'minitest/pride'
require 'commands/command_spec_base'
# application module
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'replicant'
| ruby | MIT | 9ff97d9f6909c2ceee95f30c60c4369c46a18569 | 2026-01-04T17:52:45.776762Z | false |
mttkay/replicant | https://github.com/mttkay/replicant/blob/9ff97d9f6909c2ceee95f30c60c4369c46a18569/test/process_muncher_spec.rb | test/process_muncher_spec.rb | require 'helper'
class ProcessMuncherSpec < MiniTest::Spec
ADB_SHELL_PS = <<-OUTPUT
USER PID PPID VSIZE RSS WCHAN PC NAME
root 1 0 716 480 c10b5805 0805a586 S /init
u0_a50 1247 123 562480 54296 ffffffff b75a59eb S com.soundcloud.android
u0_a27 1333 123 517564 18668 ffffffff b75a59eb S com.android.musicfx
OUTPUT
describe "Given an adb process list containing the desired process" do
before do
AdbCommand.any_instance.stubs(:execute).returns(stub(:output => ADB_SHELL_PS, :code => 0))
repl = stub(:default_package => "com.soundcloud.android")
@muncher = ProcessMuncher.new(repl)
end
it "parses the process list into a table" do
@muncher.process_table["1247"].must_equal "com.soundcloud.android"
@muncher.process_table["1333"].must_equal "com.android.musicfx"
end
it "extracts the PID for the default package" do
@muncher.find_pid.must_equal "1247"
end
end
describe "Given an adb process list without the desired process" do
before do
AdbCommand.any_instance.stubs(:execute).returns(stub(:output => ADB_SHELL_PS, :code => 0))
repl = stub(:default_package => "not in process list")
@muncher = ProcessMuncher.new(repl)
end
it "returns nil for the default package PID" do
@muncher.find_pid.must_be_nil
end
end
describe "When no default package is set" do
before do
AdbCommand.any_instance.stubs(:execute).returns(stub(:output => ADB_SHELL_PS, :code => 0))
repl = stub(:default_package => nil)
@muncher = ProcessMuncher.new(repl)
end
it "returns nil for the default package PID" do
@muncher.find_pid.must_be_nil
end
end
describe "When the targeted device is gone and ADB craps out" do
before do
AdbCommand.any_instance.stubs(:execute).returns(stub(:code => 255))
repl = stub(:default_package => "com.soundcloud.android")
@muncher = ProcessMuncher.new(repl)
end
it "returns nil for the default package PID" do
@muncher.find_pid.must_be_nil
end
end
end | ruby | MIT | 9ff97d9f6909c2ceee95f30c60c4369c46a18569 | 2026-01-04T17:52:45.776762Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.