repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
ight/bazzar
|
app/views/shared/errors.rabl
|
object false
node :errors do
{ messages: [@message] }
end
|
ight/bazzar
|
app/views/api/v1/categories/index.rabl
|
<reponame>ight/bazzar
object false
node :categories do
partial 'api/v1/categories/show', object: @categories
end
|
ight/bazzar
|
app/models/user.rb
|
class User < ApplicationRecord
rolify after_add: [:touch_updated_at], after_remove: [:touch_updated_at]
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
#Associations
has_many :cart_items, inverse_of: :user
has_many :items, through: :cart_items
before_save :set_authentication_token, if: lambda { |entry| entry[:authentication_token].blank? }
def generate_auth_token
auth_token = formulate_auth_token
# Write the token to Rails cache
Rails.cache.write(User.cached_token_key(auth_token),
self.authentication_token,
:expires_in => BazzarSettings.authentication.session_expiration_time)
# Return the hash
auth_token
end
def self.cached_token_key(auth_token)
"api/#{auth_token}"
end
def set_authentication_token
self.authentication_token = formulate_auth_token
end
def formulate_auth_token
str = Digest::SHA256.digest("#{SecureRandom.uuid}_#{Time.now.to_i}")
Base64.encode64(str).gsub(/[\s=]+/, "").tr('+/','-_')
end
def self.from_authentication_token(auth_token, renew = false)
cached_key = self.cached_token_key(auth_token)
authentication_token = Rails.cache.read cached_key
if authentication_token
user = User.find_by_authentication_token authentication_token
# Renew the token
if renew && user
Rails.cache.write cached_key, authentication_token,
expires_in: BazzarSettings.authentication.session_expiration_time
end
end
user
end
def touch_updated_at(_role)
update_column(:updated_at, Time.now)
end
end
|
ight/bazzar
|
app/views/api/v1/users/show.rabl
|
object @user
attributes :id, :first_name, :last_name, :email, :contact_number
|
ight/bazzar
|
db/migrate/20171128082554_create_items.rb
|
<reponame>ight/bazzar<gh_stars>0
class CreateItems < ActiveRecord::Migration[5.0]
def change
create_table :items do |t|
t.string :name, null: false
t.string :price, null: false
t.string :code, null: false
t.timestamps
end
add_index :items, :code, unique: true
end
end
|
ight/bazzar
|
app/models/category.rb
|
class Category < ApplicationRecord
# Associations
has_many :items, inverse_of: :category
has_many :brands, inverse_of: :category
# callbacks
after_commit :update_cat_list, on: [:create, :destroy]
# Validations
validates :category_name, uniqueness: true
# Scope
scope :active, -> { where(status: 0) }
#Enumeration
enum status: [:active, :disabled, :popular]
# Module
module Status
ACTIVE = 'active'
DISABLE = 'disabled'
POPULAR = 'popular'
end
# callbacks defination
def update_cat_list
Category.list(true)
end
# class methods
def self.list(reload = false)
Rails.cache.delete(bazzar_cat_list) if reload
Rails.cache.fetch(bazzar_cat_list, expires_in: 15.days) do
Category.active.order(id: :desc)
end
end
def self.bazzar_cat_list
"bazzar_cat_list"
end
# instance method
def disable
update_column(:status, Category::Status::DISABLE)
end
end
|
ight/bazzar
|
test/test_helper.rb
|
<reponame>ight/bazzar
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!(Minitest::Reporters::ProgressReporter.new, ENV, Minitest.backtrace_filter)
class ActionController::TestCase
include Devise::Test::ControllerHelpers
end
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
def api_key_header
{'X-API-KEY' => 'some_api_key'}
end
def setup
if @controller.present? && !@controller.instance_of?(UserSessionsController)
@request.headers['HTTP_X_API_KEY'] = 'some_api_key'
@request.host = 'ight.me'
ActiveSupport::Cache::FileStore.any_instance.stubs(:read).with("api/some_api_key").returns("prakash_auth")
end
if @controller.present? && (@controller.class <= ApplicationController) && !@controller.instance_of?(UserSessionsController)
sign_in(users(:prakash))
end
end
# Add more helper methods to be used by all tests here...
require 'mocha/setup'
require 'test_unit_extensions'
end
|
ight/bazzar
|
app/models/cart_item.rb
|
<gh_stars>0
class CartItem < ApplicationRecord
# Association
belongs_to :item, inverse_of: :cart_items
belongs_to :user, inverse_of: :cart_items
end
|
ight/bazzar
|
app/models/item.rb
|
class Item < ApplicationRecord
# Associations
belongs_to :category, inverse_of: :items
belongs_to :brand, inverse_of: :items
has_many :cart_items, inverse_of: :item
has_many :users, through: :cart_items
end
|
ight/bazzar
|
test/test_unit_extensions.rb
|
module TestUnitExtensions
def json_response
@json_response_body ||= ActiveSupport::JSON.decode @response.body
end
def assert_exception_messages(exception, message)
assert_equal message, exception.message
end
end
ActiveSupport::TestCase.send(:include, TestUnitExtensions)
|
ight/bazzar
|
config/initializers/custome_exception.rb
|
<reponame>ight/bazzar<gh_stars>0
module Bazzar
module Exception
class InvalidParameter < ArgumentError; end
class NotImplementedError < NoMethodError; end
class InsufficientPrivilege < StandardError; end
class WebhookIntegration < StandardError; end
class DocMigration < StandardError; end
end
end
|
ight/bazzar
|
test/models/category_test.rb
|
<reponame>ight/bazzar<gh_stars>0
require 'test_helper'
class CategoryTest < ActiveSupport::TestCase
# Test Association
test 'has_many items' do
assert categories(:wrist_watch).items.exists?
end
test 'has_many brands' do
assert categories(:wrist_watch).brands.exists?
end
# Test callback
test 'update_cat_list is called on create' do
category = new_category
category.expects(:update_cat_list)
category.save
end
test 'update_cat_list is called on destroy' do
category = categories(:wrist_watch)
category.expects(:update_cat_list)
category.destroy
end
# Test validations
test 'validation works' do
category = new_category
category.category_name = categories(:wrist_watch).category_name
category.save
assert_not category.valid?
assert category.errors.messages.has_key?(:category_name)
end
# Callback works
test 'update_cat_list works' do
category = categories(:wrist_watch)
Category.expects(:list)
category.update_cat_list
end
# Test class method
test 'list for reload false' do
cache = mock('cache')
key = "bazzar_cat_list"
Rails.stubs('cache').returns(cache)
cache.expects(:delete).with(key).never
cache.expects(:fetch).with(key, expires_in: 15.days)
Category.list(false)
end
test 'list for reload true' do
cache = mock('cache')
key = "bazzar_cat_list"
Rails.stubs('cache').returns(cache)
cache.expects(:delete).with(key)
cache.expects(:fetch).with(key, expires_in: 15.days)
Category.list(true)
end
# Test instance methods
test 'disable works' do
category = categories(:wrist_watch)
category_status = category.status
category.disable
assert_equal category.status, "disabled"
end
private
def new_category
Category.new( category_name: 'new category')
end
end
|
ight/bazzar
|
app/views/api/v1/categories/show.rabl
|
object @category
attributes :id, :category_name
|
ight/bazzar
|
app/controllers/api/v1/categories_controller.rb
|
<reponame>ight/bazzar<filename>app/controllers/api/v1/categories_controller.rb
class Api::V1::CategoriesController < ApplicationController
swagger_controller :categories, "Handle Categories at Bazzar"
swagger_api :create do
summary 'Add a Category to Bazzar'
param :form, :"category[category_name]", :string, :required, "Enter Category Name"
response :created
response :bad_request
response :unauthorized
response :not_acceptable
response :forbidden
response :unprocessable_entity
end
def create
raise Bazzar::Exception::InvalidParameter.new(_('errors.categories.invalid_category_name')) if category_params[:category_name].blank?
@category = Category.new(category_params)
if @category.save
render 'show', status: :created
else
render 'shared/model_errors', locals: { object: @category }, status: :bad_request
end
end
swagger_api :index do
summary 'List all the categories at Bazzar'
response :ok
response :bad_request
end
def index
@categories = Category.list
end
swagger_api :destroy do
summary 'Remove a category from Bazzar'
param :query, :category_id, :integer, :required, 'category id'
response :ok
response :bad_request
response :forbidden
response :unprocessable_entity
end
def destroy
@category = Category.find(params[:category_id])
if @category.disable
head :ok
else
render 'shared/model_errors', locals: { object: @category }, status: :bad_request
end
end
private
def category_params
params.require(:category).permit(:category_name)
end
end
|
ight/bazzar
|
app/models/brand.rb
|
class Brand < ApplicationRecord
# Associations
belongs_to :category, inverse_of: :brands
has_many :items, inverse_of: :brand
end
|
ight/bazzar
|
app/controllers/bazzar_controller.rb
|
<reponame>ight/bazzar<filename>app/controllers/bazzar_controller.rb
class BazzarController < ApplicationController
skip_before_action :authenticate_user_token!
def index
render layout: false
end
def welcome
render layout: false
end
end
|
ight/bazzar
|
app/controllers/api/v1/items_controller.rb
|
<gh_stars>0
class Api::V1::ItemsController < ApplicationController
swagger_controller :items, "Handle Item Actions"
swagger_api :create do
summery 'Add an Item to Bazzar'
end
end
|
ight/bazzar
|
db/migrate/20171129071621_add_columns_to_tables.rb
|
<reponame>ight/bazzar
class AddColumnsToTables < ActiveRecord::Migration[5.0]
def change
add_column :items, :brand_id, :integer
add_column :items, :category_id, :integer
add_column :brands, :category_id, :integer
add_index :items, :brand_id
add_index :items, :category_id
add_index :brands, :category_id
end
end
|
ight/bazzar
|
app/controllers/api/v1/users_controller.rb
|
<reponame>ight/bazzar<filename>app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < ApplicationController
# Checking authorization
load_and_authorize_resource :user
swagger_controller :users, "For User actions"
swagger_api :profile do
summary 'Fetches the profile details of current user'
response :ok
response :unauthorized
response :not_acceptable
end
def profile
@user = current_user
render :show
end
end
|
ight/bazzar
|
config/initializers/swagger_docs.rb
|
<filename>config/initializers/swagger_docs.rb
# Overriding the transform_path method in this class
class Swagger::Docs::Config
def self.transform_path(path, api_version)
"api/v#{api_version.to_i}/#{path}"
end
Swagger::Docs::Config.base_api_controller = ApplicationController
Swagger::Docs::Config.register_apis({
"1.0" => {
# Base Controller for API
base_api_controller: ApplicationController,
# The extension used for the API
api_extension_type: :json,
# Location where the .json files will be store
api_file_path: "public/api/v1/",
# Base path for api url
base_path: BazzarSettings.url,
# If you want to delete all .json files at each generation
clean_directory: false
}
})
end
|
ight/bazzar
|
config/initializers/1_bazzar_settings.rb
|
class BazzarSettings < Settingslogic
# Load the source file for settings
source "#{Rails.root}/config/bazzar.yml"
namespace Rails.env
def self.build_url
custom_port = ":#{port}" unless [443.80].include?(port.to_i)
app_path =
[ protocol,
"://",
host,
custom_port,
relative_url_root
].join('')
end
end
BazzarSettings['host'] ||= 'localhost'
BazzarSettings['relative_url'] ||= '/'
BazzarSettings['url'] ||= BazzarSettings.build_url
BazzarSettings['authentication'] ||= Settingslogic.new({})
BazzarSettings.authentication['session_expiration_time'] ||= 520
|
ight/bazzar
|
db/migrate/20171130103047_add_index_to_user.rb
|
<gh_stars>0
class AddIndexToUser < ActiveRecord::Migration[5.0]
def change
add_index :users, :contact_number
add_index :users, :email
add_index :cart_items, :item_id
add_index :cart_items, :user_id
end
end
|
ight/bazzar
|
db/migrate/20171130095127_create_cart_items.rb
|
class CreateCartItems < ActiveRecord::Migration[5.0]
def change
create_table :cart_items do |t|
t.integer :item_id
t.integer :user_id
t.boolean :processed, null: false, default: false
t.timestamps
end
end
end
|
ight/bazzar
|
app/controllers/application_controller.rb
|
<reponame>ight/bazzar<filename>app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Swagger::Docs::ImpotentMethods
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception, unless: -> { request.format.json? }
before_action :authenticate_user!
rescue_from Bazzar::Exception::InvalidParameter, with: :invalid_parameter
def render_error_json(message, status = :bad_request)
render json: { error: message }, status: status
end
def invalid_parameter(exception)
render_error_json(exception.message)
end
def authenticate_user!
unauthorized_access if current_user.blank?
end
def unauthorized_access
render_error_json(_('errors.unauthorized'), :unauthorized)
end
def current_user
User.from_authentication_token(request.env["HTTP_X_API_KEY"], true)
@current_user ||= User.from_authentication_token(request.env["HTTP_X_API_KEY"], true)
end
end
|
ight/bazzar
|
app/controllers/users/registrations_controller.rb
|
<filename>app/controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
skip_before_action :verify_authenticity_token
before_filter :configure_permitted_parameters
# skip_before_action :authenticate_user_token!, only: [:create]
respond_to :json
#Add this line
swagger_controller :user_registrations, "Registrations"
#Add this swagger_api block
swagger_api :create do
summary "Creates a new User"
param :form, :'user[first_name]', :string, "First name"
param :form, :'user[last_name]', :string, "Last name"
param :form, :'user[email]', :string, :required, "Email address"
param :form, :'user[password]', :string, :required, "Password"
param :form, :'user[password_confirmation]', :string, :required, "Password Confirmation"
param :form, :'user[contact_number]', :string, :required, "Phone Number"
response :unauthorized
response :not_acceptable
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:contact_number, :email, :first_name, :last_name, :password, :password_confirmation, :authentication_token])
end
end
|
ight/bazzar
|
test/controllers/api/v1/categories_controller_test.rb
|
<reponame>ight/bazzar<filename>test/controllers/api/v1/categories_controller_test.rb<gh_stars>0
require 'test_helper'
class Api::V1::CategoriesControllerTest < ActionController::TestCase
test 'create' do
post :create, params: { category: { category_name: 'sample category' } }
assert_response :created
[:id, :category_name].each do |attr|
assert json_response["category"].has_key?(attr.to_s), "The key #{attr.to_s} was not present"
end
end
test 'create errors fails for no name' do
post :create, params: { category: { category_name: nil } }
assert_equal _('errors.categories.invalid_category_name'), json_response['error']
end
test 'create fails for duplicate name' do
category = categories(:wrist_watch)
post :create, params: { category: { category_name: category.category_name } }
assert_equal json_response['errors']['messages'].first, "Category name has already been taken"
end
test 'index' do
get :index
assert_response :ok
assert_template :index
[:id, :category_name].each do |attr|
assert json_response["categories"][0].has_key?(attr.to_s), "The key #{attr.to_s} was not present"
end
end
test 'destroy' do
category = categories(:wrist_watch)
delete :destroy, params: { category_id: category.id }
assert_response :ok
end
end
|
joaodrp/homebrew-tap
|
Formula/gelf-pretty.rb
|
<filename>Formula/gelf-pretty.rb
# This file was generated by GoReleaser. DO NOT EDIT.
class GelfPretty < Formula
desc "CLI to pretty-print Graylog Extended Log Format (GELF) log lines"
homepage "https://github.com/joaodrp/gelf-pretty"
url "https://github.com/joaodrp/gelf-pretty/releases/download/v0.1.0/gelf-pretty_0.1.0_Darwin_x86_64.tar.gz"
version "0.1.0"
sha256 "934892fcab183259dbffced84a3d02717ddc4972a59c5a28bd9b200e7ac8ec0c"
def install
bin.install "gelf-pretty"
end
test do
system "#{bin}/gelf-pretty --version"
end
end
|
Salvador-ON/Build-Your-Own-Scraper
|
lib/write_file.rb
|
# frozen_string_literal: true
# Writting txt file
class Filewrite
attr_reader :file
def initialize(search_arr)
prefix = 'searches/search-related-to-'
@file = File.open(prefix + "#{search_arr.join('-')}.html", 'w')
end
def build_html
File.open('template/begin.txt').each do |line|
@file.puts line
end
end
def classify(list_title, list_ref)
ph1 = '<h3><a href="'
ph2 = '"style="color:black;">'
ph3 = '</a></h3>'
(0...list_title.length).each do |n|
@file.puts "#{ph1}#{list_ref[n]}#{ph2}#{list_title[n]}#{ph3}"
end
end
def end_html
File.open('template/end.txt').each do |line|
@file.puts line
end
end
def close_file
@file.close
end
end
|
Salvador-ON/Build-Your-Own-Scraper
|
lib/browser.rb
|
# frozen_string_literal: true
# Browser Class, search for the target elements and save it in an array
class Browser
attr_reader :parsed_page, :last_page, :titles, :titles_arr
attr_reader :ref_arr, :art_in_page
def initialize
@browser = Watir::Browser.new
@browser.goto 'https://hackernoon.com/tagged/ruby'
@titles_arr = []
@ref_arr = []
end
def parsed
@browser.element(css: 'div#stats').wait_until(&:present?)
@parsed_page = Nokogiri::HTML(@browser.html)
end
def parsed_wait
@browser.element(css: 'div#stats').wait_until(&:present?)
sleep(1)
@parsed_page = Nokogiri::HTML(@browser.html)
end
def check_titles_inpage
@titles = @parsed_page.css('div.stories-item')
@art_in_page = titles.count
end
def check_total_pages
total_articles = @parsed_page.css('div#stats').text.split(' ')[0].to_i
@last_page = (total_articles / @art_in_page.to_f).round
@last_page
end
# rubocop: disable Metrics/AbcSize
def scrap_page(s_arr)
@parsed_page.css('div.stories-item').each do |title|
list_title = title.css('h2 a').text
url = 'https://hackernoon.com'
list_ref = url + title.css('h2 a')[0].attributes['href'].text
list = { title: list_title, ref: list_ref }
if s_arr.all? { |i| list[:title].downcase.split.include?(i) }
@titles_arr.push(list[:title])
@ref_arr.push(list[:ref])
end
end
end
# rubocop: enable Metrics/AbcSize
def change_page(page)
@browser.link(aria_label: 'Next').click if page < @last_page
end
def close_window
@browser.close
end
end
|
Salvador-ON/Build-Your-Own-Scraper
|
spec/browser_spec.rb
|
# frozen_string_literal: true
require './lib/browser.rb'
require 'nokogiri'
require 'open-uri'
require 'webdrivers'
require 'watir'
# rubocop: disable Metrics/BlockLength
RSpec.describe Browser do
describe '#Browser' do
context 'when is initialize give true if the 2 arrays init' do
test = Browser.new
test.close_window
it { expect(test.titles_arr.empty? && test.ref_arr.empty?).to eq(true) }
end
end
describe '#check_titles_inpage' do
context 'when is call give true if parse is correct & title count match' do
test = Browser.new
test.parsed
test.check_titles_inpage
test.close_window
it { expect(test.art_in_page).to eq(18) }
end
end
describe '#check_total_pages' do
context 'when is call give true ' do
test = Browser.new
test.parsed
test.check_titles_inpage
test.check_total_pages
test.close_window
it { expect((true if test.last_page > 0)).to eq(true) }
end
end
describe '#scrap_page' do
context 'when is call give true ' do
test = Browser.new
test.parsed
test.scrap_page(%w[ruby])
test.close_window
it { expect((test.titles_arr.any? && test.ref_arr.any?)).to eq(true) }
end
end
describe '#scrap_page' do
context 'when is call give true ' do
test = Browser.new
test.parsed
test.check_titles_inpage
test.check_total_pages
test.scrap_page(%w[ruby])
count1 = test.titles_arr.count
test.change_page(1)
test.scrap_page(%w[ruby])
count2 = test.titles_arr.count
test.close_window
it { expect((true if count2 > count1)).to eq(true) }
end
end
end
# rubocop: enable Metrics/BlockLength
|
Salvador-ON/Build-Your-Own-Scraper
|
spec/write_file_spec.rb
|
# frozen_string_literal: true
require './lib/write_file.rb'
# rubocop: disable Metrics/BlockLength
RSpec.describe Filewrite do
arr1 = %w[RSPEC-TEST-ruby rails]
p_name = 'searches/search-related-to-' + "#{arr1.join('-')}.html"
describe '#Filewrite' do
context 'when is initialize create a new file give true' do
write = Filewrite.new(arr1)
write.close_file
it { expect(File.file?(p_name)).to eq(true) }
end
end
describe '#build_html' do
write = Filewrite.new(arr1)
write.build_html
write.close_file
context 'when build is call write text & file give true' do
it { expect(File.foreach(p_name).grep(/html/).any?).to eq(true) }
end
end
describe '#classify' do
write = Filewrite.new(arr1)
write.classify(arr1, arr1)
write.close_file
context 'when classify is call write text & file give true' do
it { expect(File.foreach(p_name).grep(/ruby/).any?).to eq(true) }
end
end
describe '#end_html' do
write = Filewrite.new(arr1)
write.end_html
write.close_file
context 'when end is call write text & file give true' do
it { expect(File.foreach(p_name).grep(/body/).any?).to eq(true) }
end
end
describe '#close_file' do
write = Filewrite.new(arr1)
write.build_html
write.classify(arr1, arr1)
write.close_file
context 'when classify in call write text file gibe true' do
it { expect(write.file.closed?).to eq(true) }
end
end
end
# rubocop: enable Metrics/BlockLength
|
Salvador-ON/Build-Your-Own-Scraper
|
bin/main.rb
|
<filename>bin/main.rb
# frozen_string_literal: true
require 'nokogiri'
require 'open-uri'
require 'byebug'
require 'webdrivers'
require 'watir'
require_relative '../lib/browser.rb'
require_relative '../lib/write_file.rb'
# Start class that initizalize everything
class Start
attr_reader :page, :write
def initialize
@page = 1
end
private
def validate_input
puts 'Search Hackernoon coding articles related to keywords'
puts 'Enter keywords separated with spaces eg. kw1 kw2'
input = gets.chomp
while input.empty?
puts 'Try again invalid input'
puts 'Enter keywords separated with spaces eg. kw1 kw2'
input = gets.chomp
end
@search_input_arr = input.split(' ')
end
public
def start_search
validate_input
@start = Browser.new
@start.parsed
@start.check_titles_inpage
@last_page = @start.check_total_pages
end
# rubocop: disable Metrics/MethodLength
def writing_search
write = Filewrite.new(@search_input_arr)
write.build_html
while @page <= @last_page
@start.parsed_wait
@start.scrap_page(@search_input_arr)
@start.change_page(@page)
@page += 1
end
write.classify(@start.titles_arr, @start.ref_arr)
write.end_html
write.close_file
@start.close_window
show_results
end
# rubocop: enable Metrics/MethodLength
private
def show_results
puts ''
puts 'I finished the search'
puts "Related to the key words #{@search_input_arr.join(' ')}\n\n"
puts "I found #{@start.titles_arr.count} articles related\n\n"
puts "These are the articles that I found:\n\n"
puts @start.titles_arr
puts ''
puts 'To visualize the articles go to the searches folder'
puts "And open search-related-to-#{@search_input_arr.join('-')}.html\n\n"
new_search
end
def new_search
puts "if you want to start a new search type: Y\n\n"
puts "if you want to close the program type any other character\n\n"
user_ans = gets.chomp.upcase
search_again if user_ans == 'Y'
end
def search_again
new_search = Start.new
new_search.start_search
new_search.writing_search
end
end
new_search = Start.new
new_search.start_search
new_search.writing_search
|
youssef-abdallah/Reddit-Clone
|
app/controllers/communities_controller.rb
|
class CommunitiesController < ApplicationController
before_action :authenticate_account!, except: [:show, :index]
before_action :set_community, only: [:show]
def index
@communities = Community.all
end
def show
@posts = @community.posts
end
def new
@community = Community.new
end
def create
@community = Community.new community_params
@community.account_id = current_account.id
if @community.save
redirect_to communities_path
else
render 'new'
end
end
private
def set_community
@community = Community.find(params[:id])
end
def community_params
params.require(:community).permit(:name, :url, :rules)
end
end
|
youssef-abdallah/Reddit-Clone
|
app/models/post.rb
|
<reponame>youssef-abdallah/Reddit-Clone
class Post < ApplicationRecord
belongs_to :account
belongs_to :community
validates_presence_of :title, :body, :account_id, :community_id
end
|
youssef-abdallah/Reddit-Clone
|
app/controllers/public_controller.rb
|
<reponame>youssef-abdallah/Reddit-Clone<gh_stars>0
class PublicController < ApplicationController
def index
@communities = Community.all.limit(5)
@posts = Post.order(id: :desc).limit(20)
end
end
|
youssef-abdallah/Reddit-Clone
|
app/models/community.rb
|
<filename>app/models/community.rb
class Community < ApplicationRecord
belongs_to :account
has_many :posts
validates :name, presence: true
validates :url, presence: true
validates :rules, presence: true
end
|
youssef-abdallah/Reddit-Clone
|
config/routes.rb
|
Rails.application.routes.draw do
devise_for :accounts
resources :communities do
resources :posts
end
root to: "public#index"
end
|
andypayne/basicsom
|
lib/som_main.rb
|
require './som_view_html.rb'
################################################################################
# Defaults
win_width = 400
win_height = 400
x_num_nodes = 40
y_num_nodes = 40
# RGB
input_vec_size = 3
num_iterations = 1000
init_learning_rate = 0.1
input_file_name = ""
output_file_name = ""
output_file = nil
rand_entropy = 1234
interactive_mode = false
start_paused = false
################################################################################
puts "-------------------"
puts "Self-Organizing Map"
puts "-------------------\n\n"
opts = OptionParser.new
opts.on("-i", "--in FILE", "Specify input CSV FILE.", String) { |val| input_file_name = val }
opts.on("-o", "--out FILE", "Specify output FILE (default is $stdout).", String) { |val| output_file_name = val }
opts.on("-s", "--invecsize VAL", "Specify input vector size (default is #{input_vec_size}).", Integer) { |val| input_vec_size = val }
opts.on("-n", "--numiterations VAL", "Number of iterations (default is #{num_iterations}).", Integer) { |val| num_iterations = val }
opts.on("-l", "--learnrate VAL", "Specify initial learning rate (default is #{init_learning_rate}).", Float) { |val| init_learning_rate = val }
opts.on("-x", "--xnodes VAL", "Specify number of nodes in X (default is #{x_num_nodes}).", Integer) { |val| x_num_nodes = val }
opts.on("-y", "--ynodes VAL", "Specify number of nodes in Y (default is #{y_num_nodes}).", Integer) { |val| y_num_nodes = val }
opts.on("-w", "--width VAL", "Specify width of area. (default is #{win_width})", Integer) { |val| win_width = val }
opts.on("-e", "--height VAL", "Specify height of area (default is #{win_height}).", Integer) { |val| win_height = val }
opts.on("-r", "--randseed VAL", "Specify the seed value for srand() (default is #{rand_entropy}).", Integer) { |val| rand_entropy = val }
opts.on("-c", "--interactive", "Run interactively (default is off).") { |val| interactive_mode = true }
opts.on("-p", "--paused", "Start paused, for interactive mode (default is off).") { |val| start_paused = true }
opts.on_tail("-h", "-?", "--help", "Display help message.") { |val| puts opts.to_s; exit }
begin
rest = opts.parse(ARGV)
# if bulk_download
# url_list = rest
# end
rescue OptionParser::InvalidOption => detail
puts "Error: #{detail.to_s}.\n\n"
puts opts.to_s
exit
end
if input_file_name.size == 0
puts "Error: You must specify an input CSV file.\n\n"
puts opts.to_s
exit
end
if output_file_name.size == 0
output_file = $stdout
else
output_file = File.open(output_file_name, "w")
end
################################################################################
input_vector = []
input_vector = CSV.read(input_file_name)
# TODO: Use something else here.
input_vector.each_index { |i|
input_vector[i].each_index { |j|
input_vector[i][j] = input_vector[i][j].to_f
}
}
# Use the size of the first row for the input vector size.
input_vec_size = input_vector[0].size
srand(rand_entropy)
som = Som.new(win_width,
win_height,
x_num_nodes,
y_num_nodes,
num_iterations,
input_vec_size,
init_learning_rate)
som_view = SomViewHtml.new(som)
som.set_inputs(input_vector)
som_view.paused = true if start_paused
if interactive_mode == true
server = WEBrick::HTTPServer.new(:Port => 8081)
server.mount_proc("/som") { |req, resp|
resp.status = 200
resp['Content-Type'] = 'text/html'
resp.body = som_view.render2()
}
server.mount_proc("/update_som") { |req, resp|
resp.status = 200
resp['Content-Type'] = 'text/plain'
som_view.paused = false
resp.body = "#{som.iteration_index}|" + som_view.grid_to_tbl()
}
trap("INT") { server.shutdown(); exit }
thrd = Thread.new() {
server.start()
}
som.run_epoch() {
while (som_view.paused?)
sleep(1)
end
}
thrd.join()
else
som.run_epoch()
som_view.render(output_file)
output_file.close()
end
|
andypayne/basicsom
|
lib/som.rb
|
<filename>lib/som.rb<gh_stars>1-10
require 'csv'
require 'optparse'
require 'webrick'
require './math_help.rb'
################################################################################
class SomNode
attr_reader :weights, :dx, :dy
def initialize(num_weights, left, right, top, bottom)
@weights = Array.new
# Random weights
num_weights.times {
@weights.push(rand())
}
@edge_left = left
@edge_right = right
@edge_top = top
@edge_bottom = bottom
@dx = @edge_left + (@edge_right - @edge_left)/2.0
@dy = @edge_top + (@edge_bottom - @edge_top)/2.0
end
def distance_from(input)
# input should be equal in length to @weights.
# assert(input.size == @weights.size)
return euclidean_dist_sq(input, @weights)
end
def adjust_weights(target, learn_rate, influence)
# assert(target.size == @weights.size)
target.each_index { |i|
@weights[i] += learn_rate * influence * (target[i] - @weights[i])
}
end
def to_rgb
return [ @weights[0]*255,
@weights[1]*255,
@weights[2]*255 ]
end
def render
r, g, b = to_rgb()
puts "RGB: (#{r}, #{g}, #{b})"
end
end
################################################################################
class Som
attr_accessor :iteration_index, :nodes, :x_num_nodes
def initialize(x_size,
y_size,
x_num_nodes,
y_num_nodes,
num_iterations,
input_vec_size,
learning_rate)
@x_size = x_size
@y_size = y_size
@x_num_nodes = x_num_nodes
@y_num_nodes = y_num_nodes
@cell_width = @x_size/@x_num_nodes
@cell_height = @y_size/@y_num_nodes
@num_iterations = num_iterations
@iteration_index = 0
@input_vec_size = input_vec_size
@learning_rate = learning_rate
@init_learning_rate = learning_rate
@nodes = Array.new
x_num_nodes.times { |i|
y_num_nodes.times { |j|
@nodes.push(SomNode.new(@input_vec_size,
j*@cell_width,
(j+1)*@cell_width,
i*@cell_height,
(i+1)*@cell_height))
}
}
@map_radius = max(@x_size, @y_size)/2
@time_constant = @num_iterations.to_f/Math.log(@map_radius)
@inputs = Array.new
end
def set_inputs(inputs)
@inputs = inputs
end
# Given an array of input vectors, ...
def run_epoch(&block)
# assert(inputs[0].size == @input_vec_size)
@num_iterations.times { |iter|
invec_idx = rand(@inputs.size)
winning_node_idx = find_best_match(@inputs[invec_idx])
neighborhood_radius = @map_radius*Math.exp(-(iter.to_f + 1.0)/@time_constant)
@nodes.each_index { |i|
dist_to_best_match = (@nodes[winning_node_idx].dx - @nodes[i].dx)**2 +
(@nodes[winning_node_idx].dy - @nodes[i].dy)**2
if dist_to_best_match < neighborhood_radius**2
influence = Math.exp(-dist_to_best_match/(2.0*(neighborhood_radius.to_f**2)))
@nodes[i].adjust_weights(@inputs[invec_idx], @learning_rate, influence)
end
}
@learning_rate = @init_learning_rate*Math.exp(-(iter.to_f + 1.0)/@num_iterations)
@iteration_index += 1
block.call() if block_given?
}
end
def find_best_match(vec)
best_match_idx = 0
best_match_dist = 0
@nodes.each_index { |i|
if i == 0
best_match_dist = @nodes[i].distance_from(vec)
else
dist = @nodes[i].distance_from(vec)
if dist < best_match_dist
best_match_dist = dist
best_match_idx = i
end
end
}
return best_match_idx
end
end
|
andypayne/basicsom
|
lib/som_view_html.rb
|
<reponame>andypayne/basicsom
require './som.rb'
################################################################################
$html_page_data =<<END_HTML_BLOCK
<html>
<head>
<script type="text/javascript">
function CreateReqObject() {
var ro;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} else {
ro = new XMLHttpRequest();
}
return ro;
}
var http = CreateReqObject();
function SendReq(action) {
if (ContinueUpdate() == true) {
http.open('get', '/update_som');
http.onreadystatechange = HandleResp;
http.send(null);
}
}
function HandleResp() {
if (http.readyState == 4) {
var response = http.responseText;
if (response.indexOf('|' != -1)) {
var update = new Array();
update = response.split('|');
document.getElementById("iter").innerHTML = "Iteration: " + update[0];
document.getElementById("somtbl").innerHTML = update[1];
}
}
}
var bContinueUpdate = true;
function ContinueUpdate() {
return bContinueUpdate;
}
function TimerSendReq() {
if (ContinueUpdate() == true) {
SendReq('update');
setTimeout('TimerSendReq()', 3000);
}
}
function ToggleUpdate() {
if (document.getElementById("updatelnk").innerHTML == "Pause")
{
bContinueUpdate = false;
document.getElementById("updatelnk").innerHTML = "Continue";
}
else
{
bContinueUpdate = true;
setTimeout('TimerSendReq()', 3000);
document.getElementById("updatelnk").innerHTML = "Pause";
}
}
function UpdateCellVal(str) {
document.getElementById('cellvals').innerHTML = '(' + str + ')';
}
</script>
<style type="text/css">
td {
font-size: 4px;
line-height: 1px;
border: 1px solid transparent;
}
.bordered {
border: 1px solid #000;
}
.legborder {
border: 1px solid #000;
}
</style>
</head>
END_HTML_BLOCK
class SomViewHtml
attr_accessor :paused
def initialize(som)
@som = som
@input_legend = ""
@paused = false
end
def paused?
return @paused
end
def grid_to_tbl()
str = "<tr>\n"
@som.nodes.each_index { |i|
if i % @som.x_num_nodes == 0
str += "</tr>\n<tr>\n"
end
r, g, b = @som.nodes[i].to_rgb()
str += "<td bgcolor=\"#{sprintf("%02x", r)}#{sprintf("%02x", g)}#{sprintf("%02x", b)}\" onClick=\"javascript:UpdateCellVal('#{@som.nodes[i].weights.join(", ")}')\"> </td>"
}
str += "</tr>\n"
return str
end
def meta_to_str()
str = String.new
str += "\n<p id=\"iter\">Iteration: #{@som.iteration_index}</p>\n"
str += "\n<br>Cell values:\n<p id=\"cellvals\"></p>\n"
str += "\n<br>\nInput Values:\n"
str += "<table class=\"legborder\" cellpadding=\"4\" cellspacing=\"3\">\n<tr>\n"
str += @input_legend
str += "</tr>\n</table>\n"
return str
end
def render(stream)
calc_input_legend()
stream.puts $html_page_data
stream.puts "<body onload=\"javascript:setTimeout('TimerSendReq()', 3000)"
if paused?
stream.puts ';bContinueUpdate=false">'
else
stream.puts '">'
end
stream.puts '<a href="#" onclick="javascript:ToggleUpdate()" id="updatelnk">'
if paused?
stream.puts 'Continue</a>'
else
stream.puts 'Pause</a>'
end
stream.puts "<br />"
stream.puts '<table id="somtbl" border="0" cellpadding="4" cellspacing="3">'
stream.puts som.grid_to_tbl()
stream.puts "</table>"
stream.puts som.meta_to_str()
stream.puts "</body></html>"
end
# TODO: Hack. Clean this up.
def render2()
str = $html_page_data
str += '<body onload="javascript:setTimeout(\'TimerSendReq()\', 3000)'
if paused?
str += ';bContinueUpdate=false">'
else
str += '">'
end
str += '<a href="#" onclick="javascript:ToggleUpdate()" id="updatelnk">'
if paused?
str += 'Continue</a>'
else
str += 'Pause</a>'
end
str += "<br />"
str += '<table id="somtbl" border="0" cellpadding="4" cellspacing="3">'
str += grid_to_tbl()
str += "</table>"
str += meta_to_str()
str += "</body></html>"
return str
end
def calc_input_legend()
# Hack to save inputs for the legend.
@som.inputs.each { |vec|
@input_legend += "<td bgcolor=\"#{sprintf("%02x", vec[0]*255)}#{sprintf("%02x", vec[1]*255)}#{sprintf("%02x", vec[2]*255)}\"> </td>\n"
}
end
end
|
andypayne/basicsom
|
lib/math_help.rb
|
################################################################################
def max(a, b)
return (a > b) ? a : b
end
def min(a, b)
return (a < b) ? a : b
end
# Squared Euclidean distance
def euclidean_dist_sq(vec1, vec2)
raise "Array sizes are not the same" unless vec1.size == vec2.size
dist = 0.0
vec1.each_index { |i|
dist += (vec1[i] - vec2[i])*(vec1[i] - vec2[i])
}
return dist
end
################################################################################
|
notEthan/oauthenticator
|
lib/oauthenticator/rack_test_signer.rb
|
module OAuthenticator
module RackTestSigner
# takes a block. for the duration of the block, requests made with Rack::Test will be signed
# with the given oauth_attrs. oauth_attrs are passed to {OAuthenticator::SignableRequest}.
#
# attributes of the request are set from the Rack::Test request, so you should not provide those in
# the outh_attrs.
#
# These are the options you should or may provide (see {OAuthenticator::SignableRequest} for details of
# what options are required, what options have default or generated values, and what may be omitted):
#
# - signature_method
# - consumer_key
# - consumer_secret
# - token
# - token_secret
# - version
# - realm
# - hash_body?
def signing_rack_test(oauth_attrs, &block)
begin
Thread.current[:oauthenticator_rack_test_attributes] = oauth_attrs
return yield
ensure
Thread.current[:oauthenticator_rack_test_attributes] = nil
end
end
end
# you can run OAuthenticator.signing_rack_test(attrs) { stuff }
extend RackTestSigner
end
class Rack::Test::Session
actual_process_request = instance_method(:process_request)
remove_method(:process_request)
define_method(:process_request) do |uri, env, &block|
oauth_attrs = Thread.current[:oauthenticator_rack_test_attributes]
if oauth_attrs
request = Rack::Request.new(env)
env['HTTP_AUTHORIZATION'] = OAuthenticator::SignableRequest.new(oauth_attrs.merge({
:request_method => request.request_method,
:uri => request.url,
:media_type => request.media_type,
:body => request.body,
})).authorization
end
actual_process_request.bind(self).call(uri, env, &block)
end
end
|
notEthan/oauthenticator
|
test/config_methods_test.rb
|
# encoding: utf-8
proc { |p| $:.unshift(p) unless $:.any? { |lp| File.expand_path(lp) == p } }.call(File.expand_path('.', File.dirname(__FILE__)))
require 'helper'
describe OAuthenticator::SignedRequest do
%w(timestamp_valid_period consumer_secret token_secret nonce_used? use_nonce! token_belongs_to_consumer?).each do |method_without_default|
it "complains when #{method_without_default} is not implemented" do
exc = assert_raises(NotImplementedError) do
OAuthenticator::SignedRequest.new({}).public_send(method_without_default)
end
assert_match(/included in a subclass of OAuthenticator::SignedRequest/, exc.message)
end
it "uses the method #{method_without_default} when implemented" do
called = false
mod = Module.new { define_method(method_without_default) { called = true } }
OAuthenticator::SignedRequest.including_config(mod).new({}).public_send(method_without_default)
assert called
end
end
it "complains when a method without a default is not implemented, using RackAuthenticator" do
exc = assert_raises(NotImplementedError) do
OAuthenticator::RackAuthenticator.new(proc {}, {:config_methods => Module.new}).call({'HTTP_AUTHORIZATION' => %q(OAuth oauth_timestamp="1")})
end
assert_match(/passed to OAuthenticator::RackAuthenticator using the option :config_methods./, exc.message)
end
it "complains RackAuthenticator is not given config methods" do
assert_raises(ArgumentError) do
OAuthenticator::RackAuthenticator.new(proc {})
end
end
it 'uses timestamp_valid_period if that is implemented but timestamp_valid_past or timestamp_valid_future is not' do
called = 0
mod = Module.new { define_method(:timestamp_valid_period) { called +=1 } }
OAuthenticator::SignedRequest.including_config(mod).new({}).public_send(:timestamp_valid_future)
OAuthenticator::SignedRequest.including_config(mod).new({}).public_send(:timestamp_valid_past)
assert_equal 2, called
end
it 'uses the default value for allowed signature methods' do
assert_equal %w(RSA-SHA1 HMAC-SHA256 HMAC-SHA512 HMAC-SHA1 PLAINTEXT).sort, OAuthenticator::SignedRequest.new({}).allowed_signature_methods.sort
end
it 'uses default value for body_hash_required?' do
assert_equal false, OAuthenticator::SignedRequest.new({}).body_hash_required?
end
end
|
nrsantamaria/ruby_triangle
|
spec/triangle_spec.rb
|
<gh_stars>0
require('rspec')
require('triangle')
describe('Triangle#initialize') do
it('creates a new triangle object based on the three provided side arguments') do
expect(Triangle.new(3,4,5).class).to(eq(Triangle))
end
end
describe('Triangle#type') do
it('will return the triangle type of equilateral if the given triangle objects side properties are all the same') do
expect(Triangle.new(3,3,3).type).to(eq('Equilateral'))
end
it("it will return 'not a triangle' if the given object's sides do not make a triangle (the sum of any two sides of the triangle is less than the third side)") do
expect(Triangle.new(2,2,8).type).to(eq("Not a triangle"))
end
it('will return the triangle type of isosceles if two of the triangle objects side properties are the same') do
expect(Triangle.new(2,2,3).type).to(eq("Isosceles"))
end
it('will return the triangle type of scalene if no sides are the same') do
expect(Triangle.new(3,4,5).type).to(eq("Scalene"))
end
end
|
nrsantamaria/ruby_triangle
|
lib/triangle.rb
|
<reponame>nrsantamaria/ruby_triangle
class Triangle
define_method(:initialize) do |side1, side2, side3|
@sides = [side1, side2, side3].map{|s| s.to_i}.sort
end
define_method(:type) do
if @sides.uniq.length == 1
"Equilateral"
elsif @sides[0] + @sides[1] <= @sides[2]
"Not a triangle"
elsif @sides.uniq.length == 2
"Isosceles"
else
"Scalene"
end
end
end
|
Mosaics/BAPickView
|
BAPickView.podspec
|
<reponame>Mosaics/BAPickView<gh_stars>0
Pod::Spec.new do |s|
s.name = "BAPickView"
s.version = "1.1.3"
s.summary = '目前为止,最为精简的 自定义 pickView 和 日期选择器 封装!'
s.homepage = 'https://github.com/BAHome/BAPickView'
s.license = 'MIT'
s.authors = { 'boa' => '<EMAIL>' }
s.platform = :ios, '7.0'
s.source = { :git => 'https://github.com/BAHome/BAPickView.git', :tag => s.version.to_s }
s.source_files = 'BAPickView/BAPickView/*.{h,m}'
s.requires_arc = true
s.resource = 'BAPickView/**/*.bundle'
end
|
zhuhaow/aws-sam-cli
|
tests/integration/testdata/sync/infra/before/Ruby/function/app.rb
|
require 'statistics'
require 'json'
require 'layer'
def lambda_handler(event:, context:)
# Sample pure Lambda function that returns a message and a location
normal = Statistics::Distribution::Normal.new(2,3)
{
statusCode: 200,
body: {
message: "#{layer()+1}",
extra_message: normal.random
}.to_json
}
end
|
zhuhaow/aws-sam-cli
|
tests/integration/testdata/sync/infra/before/Ruby/layer/layer.rb
|
def layer()
6
end
|
zhuhaow/aws-sam-cli
|
tests/integration/testdata/sync/infra/after/Ruby/layer/layer.rb
|
def layer()
7
end
|
substancelab/acts-as-rated
|
test/fixtures/migrations/001_add_rating_tables.rb
|
<filename>test/fixtures/migrations/001_add_rating_tables.rb
class AddRatingTables < ActiveRecord::Migration
def self.up
ActiveRecord::Base.create_ratings_table
ActiveRecord::Base.create_ratings_table :with_rater => false, :table_name => 'no_rater_ratings'
ActiveRecord::Base.create_ratings_table :with_stats_table => true, :table_name => 'stats_ratings'
ActiveRecord::Base.create_ratings_table :with_stats_table => true, :table_name => 'my_stats_ratings', :stats_table_name => 'my_statistics'
# Movies table has the columns for the ratings added
create_table(:movies) do |t|
t.column :title, :text
Movie.generate_ratings_columns t
end
# Books table doesn't have the columns for ratings added
create_table(:books) do |t|
t.column :title, :text
end
# Cars table has the columns for the ratings added, but is used for testing with no rater
create_table(:cars) do |t|
t.column :title, :text
end
Car.add_ratings_columns
# Videos table has the ratings columns added as part of the table creation
create_table(:videos) do |t|
t.column :title, :text
end
# We need a users table
create_table(:users) do |t|
t.column :title, :text
end
end
def self.down
Movie.remove_ratings_columns
Car.remove_ratings_columns
drop_table :movies rescue nil
drop_table :books rescue nil
drop_table :users rescue nil
drop_table :cars rescue nil
drop_table :videos rescue nil
ActiveRecord::Base.drop_ratings_table
ActiveRecord::Base.drop_ratings_table :table_name => 'no_rater_ratings'
ActiveRecord::Base.drop_ratings_table :with_stats_table => true, :table_name => 'stats_ratings'
ActiveRecord::Base.drop_ratings_table :with_stats_table => true, :table_name => 'my_stats_ratings', :stats_table_name => 'my_statistics'
end
end
|
substancelab/acts-as-rated
|
test/schema.rb
|
<reponame>substancelab/acts-as-rated
ActiveRecord::Schema.define(:version => 0) do
create_table :users, :force => true do |t|
t.column :title, :text
end
create_table :ratings, :force => true do |t|
t.column :rater_id, :integer
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating, :decimal
end
create_table :stats_ratings, :force => true do |t|
t.column :rater_id, :integer
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating, :decimal
end
create_table :my_stats_ratings, :force => true do |t|
t.column :rater_id, :integer
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating, :decimal
end
create_table :no_rater_ratings, :force => true do |t|
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating, :decimal
end
create_table :books, :force => true do |t|
t.column :title, :text
end
create_table :videos, :force => true do |t|
t.column :title, :text
end
create_table :movies, :force => true do |t|
t.column :title, :text
t.column :rating_count, :integer
t.column :rating_total, :decimal
t.column :rating_avg, :decimal
end
create_table :cars, :force => true do |t|
t.column :title, :text
t.column :rating_count, :integer
t.column :rating_total, :decimal
t.column :rating_avg, :decimal
end
create_table :rating_statistics, :force => true do |t|
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating_count, :integer
t.column :rating_total, :decimal
t.column :rating_avg, :decimal
end
create_table :my_statistics, :force => true do |t|
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating_count, :integer
t.column :rating_total, :decimal
t.column :rating_avg, :decimal
end
end
|
substancelab/acts-as-rated
|
lib/acts-as-rated/acts_as_rated.rb
|
module ActiveRecord #:nodoc:
module Acts #:nodoc:
# == acts_as_rated
# Adds rating capabilities to any ActiveRecord object.
# It has the ability to work with objects that have or don't special fields to keep a tally of the
# ratings and number of votes for each object.
# In addition it will by default use the User model as the rater object and keep the ratings per-user.
# It can be configured to use another class, or not use a rater at all, just keeping a global rating
#
# Special methods are provided to create the ratings table and if needed, to add the special fields needed
# to keep per-objects ratings fast for access to rated objects. Can be easily used in migrations.
#
# == Example of usage:
#
# class Book < ActiveRecord::Base
# acts_as_rated
# end
#
# bill = User.find_by_name 'bill'
# jill = User.find_by_name 'jill'
# catch22 = Book.find_by_title 'Catch 22'
# hobbit = Book.find_by_title 'Hobbit'
#
# catch22.rate 5, bill
# hobbit.rate 3, bill
# catch22.rate 1, jill
# hobbit.rate 5, jill
#
# hobbit.rating_average # => 4
# hobbit.rated_total # => 8
# hobbit.rated_count # => 2
#
# hobbit.unrate bill
# hobbit.rating_average # => 5
# hobbit.rated_total # => 5
# hobbit.rated_count # => 1
#
# bks = Book.find_by_rating 5 # => [hobbit]
# bks = Book.find_by_rating 1..5 # => [catch22, hobbit]
#
# usr = Book.find_rated_by jill # => [catch22, hobbit]
#
module Rated
class RateError < RuntimeError; end
def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
module ClassMethods
# Make the model ratable. Can work both with and without a rater entity (defaults to User).
# The Rating model, holding the details of the ratings, will be created dynamically if it doesn't exist.
#
# * Adds a <tt>has_many :ratings</tt> association to the model for easy retrieval of the detailed ratings.
# * Adds a <tt>has_many :raters</tt> association to the onject, unless <tt>:no_rater</tt> is given as a configuration parameter.
# * Adds a <tt>has_many :ratings</tt> associations to the rater class.
# * Adds a <tt>has_one :rating_statistic</tt> association to the model, if <tt>:with_stats_table => true</tt> is given as a configuration param.
#
# === Options
# * <tt>:rating_class</tt> -
# class of the model used for the ratings. Defaults to Rating. This class will be dynamically created if not already defined.
# If the class is predefined, it must have in it the following definitions:
# <tt>belongs_to :rated, :polymorphic => true</tt> and if using a rater (which is true in most cases, see below) also
# <tt>belongs_to :rater, :class_name => 'User', :foreign_key => :rater_id</tt> replace user with the rater class if needed.
# * <tt>:rater_class</tt> -
# class of the model that creates the rating.
# Defaults to User This class will NOT be created, so it must be defined in the app.
# Another option will be to keep a session or IP based ID here to prevent multiple ratings from the same client.
# * <tt>:no_rater</tt> -
# do not keep track of who created the rating. This will change the behaviour
# to one that just collects and averages ratings, but doesn't keep track of who
# posted the rating. Useful in a public application that doesn't care about
# individual votes
# * <tt>:rating_range</tt> -
# A range object for the acceptable rating value range. Defaults to not limited
# * <tt>:with_stats_table</tt> -
# Use a separate statistics table to hold the count/total/average rating of the rated object instead of adding the columns to the object's table.
# This means we do not have to change the model table. It still holds a big performance advantage over using SQL to get the statistics
# * <tt>:stats_class -
# Class of the statics table model. Only needed if <tt>:with_stats_table</tt> is set to true. Default to RatingStat.
# This class need to have the following defined: <tt>belongs_to :rated, :polymorphic => true</tt>.
# And must make sure that it has the attributes <tt>rating_count</tt>, <tt>rating_total</tt> and <tt>rating_avg</tt> and those
# must be initialized to 0 on new instances
#
def acts_as_rated(options = {})
# don't allow multiple calls
return if self.included_modules.include?(ActiveRecord::Acts::Rated::RateMethods)
send :include, ActiveRecord::Acts::Rated::RateMethods
# Create the model for ratings if it doesn't yet exist
rating_class = options[:rating_class] || 'Rating'
rater_class = options[:rater_class] || 'User'
stats_class = options[:stats_class] || 'RatingStatistic' if options[:with_stats_table]
unless Object.const_defined?(rating_class)
Object.class_eval <<-EOV
class #{rating_class} < ActiveRecord::Base
belongs_to :rated, :polymorphic => true
#{options[:no_rater] ? '' : "belongs_to :rater, :class_name => #{rater_class}, :foreign_key => :rater_id"}
end
EOV
end
unless stats_class.nil? || Object.const_defined?(stats_class)
Object.class_eval <<-EOV
class #{stats_class} < ActiveRecord::Base
belongs_to :rated, :polymorphic => true
end
EOV
end
raise RatedError, ":rating_range must be a range object" unless options[:rating_range].nil? || (Range === options[:rating_range])
# Fix Rails 3 deprecation warning
class_attribute :acts_as_rated_options, :instance_writer => false
self.acts_as_rated_options = {:rating_range => options[:rating_range],
:rating_class => rating_class,
:stats_class => stats_class,
:rater_class => rater_class }
class_eval do
has_many :ratings, :as => :rated, :dependent => :delete_all, :class_name => rating_class.to_s
has_many(:raters, :through => :ratings, :class_name => rater_class.to_s) unless options[:no_rater]
has_one(:rating_statistic, :class_name => stats_class.to_s, :as => :rated, :dependent => :delete) unless stats_class.nil?
before_create :init_rating_fields
end
# Add to the User (or whatever the rater is) a has_many ratings if working with a rater
return if options[:no_rater]
rater_as_class = rater_class.constantize
return if rater_as_class.instance_methods.include?('find_in_ratings')
rater_as_class.class_eval <<-EOS
has_many :ratings, :foreign_key => :rater_id, :class_name => #{rating_class.to_s}
EOS
end
end
module RateMethods
def self.included(base) #:nodoc:
base.extend ClassMethods
end
# Get the average based on the special fields,
# or with a SQL query if the rated objects doesn't have the avg and count fields
def rating_average
return self.rating_avg if attributes.has_key?('rating_avg')
return (rating_statistic.rating_avg || 0) rescue 0 if acts_as_rated_options[:stats_class]
avg = ratings.average(:rating)
avg = 0 if avg.nan?
avg
end
# Is this object rated already?
def rated?
return (!self.rating_count.nil? && self.rating_count > 0) if attributes.has_key? 'rating_count'
if acts_as_rated_options[:stats_class]
stats = (rating_statistic.rating_count || 0) rescue 0
return stats > 0
end
# last is the one where we don't keep the statistics - go direct to the db
!ratings.find(:first).nil?
end
# Get the number of ratings for this object based on the special fields,
# or with a SQL query if the rated objects doesn't have the avg and count fields
def rated_count
return self.rating_count || 0 if attributes.has_key? 'rating_count'
return (rating_statistic.rating_count || 0) rescue 0 if acts_as_rated_options[:stats_class]
ratings.count
end
# Get the sum of all ratings for this object based on the special fields,
# or with a SQL query if the rated objects doesn't have the avg and count fields
def rated_total
return self.rating_total || 0 if attributes.has_key? 'rating_total'
return (rating_statistic.rating_total || 0) rescue 0 if acts_as_rated_options[:stats_class]
ratings.sum(:rating)
end
# Rate the object with or without a rater - create new or update as needed
#
# * <tt>value</tt> - the value to rate by, if a rating range was specified will be checked that it is in range
# * <tt>rater</tt> - an object of the rater class. Must be valid and with an id to be used.
# If the acts_as_rated was passed :with_rater => false, this parameter is not required
def rate value, rater = nil
# Sanity checks for the parameters
rating_class = acts_as_rated_options[:rating_class].constantize
with_rater = rating_class.column_names.include? "rater_id"
raise RateError, "rating with no rater cannot accept a rater as a parameter" if !with_rater && !rater.nil?
if with_rater && !(acts_as_rated_options[:rater_class].constantize === rater)
raise RateError, "the rater object must be the one used when defining acts_as_rated (or a descendent of it). other objects are not acceptable"
end
raise RateError, "rating with rater must receive a rater as parameter" if with_rater && (rater.nil? || rater.id.nil?)
r = with_rater ? ratings.where(:rater_id => rater.id).first : nil
raise RateError, "value is out of range!" unless acts_as_rated_options[:rating_range].nil? || acts_as_rated_options[:rating_range] === value
# Find the place to store the rating statistics if any...
# Take care of the case of a separate statistics table
unless acts_as_rated_options[:stats_class].nil? || @rating_statistic.class.to_s == acts_as_rated_options[:stats_class]
self.rating_statistic = acts_as_rated_options[:stats_class].constantize.new
end
target = self if attributes.has_key? 'rating_total'
target ||= self.rating_statistic if acts_as_rated_options[:stats_class]
rating_class.transaction do
if r.nil?
rate = rating_class.new
rate.rater_id = rater.id if with_rater
if target
target.rating_count = (target.rating_count || 0) + 1
target.rating_total = (target.rating_total || 0) + value
target.rating_avg = target.rating_total.to_f / target.rating_count if attributes.has_key? 'rating_avg'
end
ratings << rate
else
rate = r
if target
target.rating_total += value - rate.rating # Update the total rating with the new one
target.rating_avg = target.rating_total.to_f / target.rating_count if attributes.has_key? 'rating_avg'
end
end
# Remove the actual ratings table entry
rate.rating = value
if !new_record?
rate.save
target.save if target
end
end
end
# Unrate the rating of the specified rater object.
# * <tt>rater</tt> - an object of the rater class. Must be valid and with an id to be used
#
# Unrate cannot be called for acts_as_rated with :with_rater => false
def unrate rater
rating_class = acts_as_rated_options[:rating_class].constantize
if !(acts_as_rated_options[:rater_class].constantize === rater)
raise RateError, "The rater object must be the one used when defining acts_as_rated (or a descendent of it). other objects are not acceptable"
end
raise RateError, "Rater must be a valid and existing object" if rater.nil? || rater.id.nil?
raise RateError, 'Cannot unrate if not using a rater' if !rating_class.column_names.include? "rater_id"
r = ratings.find(:first, :conditions => ['rater_id = ?', rater.id])
if !r.nil?
target = self if attributes.has_key? 'rating_total'
target ||= self.rating_statistic if acts_as_rated_options[:stats_class]
if target
rating_class.transaction do
target.rating_count -= 1
target.rating_total -= r.rating
if attributes.has_key? 'rating_avg'
target.rating_avg = target.rating_total.to_f / target.rating_count
target.rating_avg = 0 if target.rating_avg.nan?
end
end
end
# Removing the ratings table entry
r.destroy
target.save if !target.nil?
end
end
# Check if an item was already rated by the given rater
def rated_by? rater
rating_class = acts_as_rated_options[:rating_class].constantize
if !(acts_as_rated_options[:rater_class].constantize === rater)
raise RateError, "The rater object must be the one used when defining acts_as_rated (or a descendent of it). other objects are not acceptable"
end
raise RateError, "Rater must be a valid and existing object" if rater.nil? || rater.id.nil?
raise RateError, 'Rater must be a valid rater' if !rating_class.column_names.include? "rater_id"
ratings.where(:rater_id => rater.id).count > 0
end
# Return ratings of the item by the given rater
def rated_by rater
rating_class = acts_as_rated_options[:rating_class].constantize
if !(acts_as_rated_options[:rater_class].constantize === rater)
raise RateError, "The rater object must be the one used when defining acts_as_rated (or a descendent of it). other objects are not acceptable"
end
raise RateError, "Rater must be a valid and existing object" if rater.nil? || rater.id.nil?
raise RateError, 'Rater must be a valid rater' if !rating_class.column_names.include? "rater_id"
ratings.where(:rater_id => rater.id)
end
private
def init_rating_fields #:nodoc:
if attributes.has_key? 'rating_total'
self.rating_count ||= 0
self.rating_total ||= 0
self.rating_avg ||= 0 if attributes.has_key? 'rating_avg'
end
end
end
module ClassMethods
# Generate the ratings columns on a table, to be used when creating the table
# in a migration. This is the preferred way to do in a migration that creates
# new tables as it will make it as part of the table creation, and not generate
# ALTER TABLE calls after the fact
def generate_ratings_columns table
table.column :rating_count, :integer
table.column :rating_total, :decimal
table.column :rating_avg, :decimal, :precision => 10, :scale => 2
end
# Create the needed columns for acts_as_rated.
# To be used during migration, but can also be used in other places.
def add_ratings_columns
if !self.column_names.include? 'rating_count'
self.connection.add_column table_name, :rating_count, :integer
self.connection.add_column table_name, :rating_total, :decimal
self.connection.add_column table_name, :rating_avg, :decimal, :precision => 10, :scale => 2
self.reset_column_information
end
end
# Remove the acts_as_rated specific columns added with add_ratings_columns
# To be used during migration, but can also be used in other places
def remove_ratings_columns
if self.column_names.include? 'rating_count'
self.connection.remove_columns table_name, :rating_count, :rating_total, :rating_avg
self.reset_column_information
end
end
# Create the ratings table
# === Options hash:
# * <tt>:with_rater</tt> - add the rated_id column
# * <tt>:table_name</tt> - use a table name other than ratings
# * <tt>:with_stats_table</tt> - create also a rating statistics table
# * <tt>:stats_table_name</tt> - the name of the rating statistics table. Defaults to :rating_statistics
# To be used during migration, but can also be used in other places
def create_ratings_table options = {}
with_rater = options[:with_rater] != false
name = options[:table_name] || :ratings
stats_table = options[:stats_table_name] || :rating_statistics if options[:with_stats_table]
self.connection.create_table(name) do |t|
t.column(:rater_id, :integer) unless !with_rater
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating, :decimal
end
self.connection.add_index(name, :rater_id) unless !with_rater
self.connection.add_index name, [:rated_type, :rated_id]
unless stats_table.nil?
self.connection.create_table(stats_table) do |t|
t.column :rated_id, :integer
t.column :rated_type, :string
t.column :rating_count, :integer
t.column :rating_total, :decimal
t.column :rating_avg, :decimal, :precision => 10, :scale => 2
end
self.connection.add_index stats_table, [:rated_type, :rated_id]
end
end
# Drop the ratings table.
# === Options hash:
# * <tt>:table_name</tt> - the name of the ratings table, defaults to ratings
# * <tt>:with_stats_table</tt> - remove the special rating statistics as well
# * <tt>:stats_table_name</tt> - the statistics table name. Defaults to :rating_statistics
# To be used during migration, but can also be used in other places
def drop_ratings_table options = {}
name = options[:table_name] || :ratings
stats_table = options[:stats_table_name] || :rating_statistics if options[:with_stats_table]
self.connection.drop_table name
self.connection.drop_table stats_table unless stats_table.nil?
end
# Find all ratings for a specific rater.
# Will raise an error if this acts_as_rated is without a rater.
def find_rated_by rater
rating_class = acts_as_rated_options[:rating_class].constantize
raise RateError, "The rater object must be the one used when defining acts_as_rated (or a descendent of it). other objects are not acceptable" if !(acts_as_rated_options[:rater_class].constantize === rater)
raise RateError, 'Cannot find_rated_by if not using a rater' if !rating_class.column_names.include? "rater_id"
raise RateError, "Rater must be an existing object with an id" if rater.id.nil?
rated_class = ActiveRecord::Base.send(:class_of_active_record_descendant, self).to_s
conds = [ 'rated_type = ? AND rater_id = ?', rated_class, rater.id ]
acts_as_rated_options[:rating_class].constantize.find(:all, :conditions => conds).collect {|r| r.rated_type.constantize.find_by_id r.rated.id }
end
# Find by rating - pass either a specific value or a range and the precision to calculate with
# * <tt>value</tt> - the value to look for or a range
# * <tt>precision</tt> - number of decimal digits to round to. Default to 10. Use 0 for integer numbers comparision
# * <tt>round_it</tt> - round the rating average before comparing?. Defaults to true. Passing false will result in a faster query
def find_by_rating value, precision = 10, round = true
rating_class = acts_as_rated_options[:rating_class].constantize
if column_names.include? "rating_avg"
if Range === value
conds = round ? [ 'round(rating_avg, ?) BETWEEN ? AND ?', precision.to_i, value.begin, value.end ] :
[ 'rating_avg BETWEEN ? AND ?', value.begin, value.end ]
else
conds = round ? [ 'round(rating_avg, ?) = ?', precision.to_i, value ] : [ 'rating_avg = ?', value ]
end
find :all, :conditions => conds
else
if round
base_sql = <<-EOS
select #{table_name}.*,round(COALESCE(average,0), #{precision.to_i}) AS rating_average from #{table_name} left outer join
(select avg(rating) as average, rated_id
from #{rating_class.table_name}
where rated_type = '#{base_class}'
group by rated_id) as rated
on rated_id=id
EOS
else
base_sql = <<-EOS
select #{table_name}.*,COALESCE(average,0) AS rating_average from #{table_name} left outer join
(select avg(rating) as average, rated_id
from #{rating_class.table_name}
where rated_type = '#{base_class}'
group by rated_id) as rated
on rated_id=id
EOS
end
if Range === value
if round
where_part = " WHERE round(COALESCE(average,0), #{precision.to_i}) BETWEEN #{connection.quote(value.begin)} AND #{connection.quote(value.end)}"
else
where_part = " WHERE COALESCE(average,0) BETWEEN #{connection.quote(value.begin)} AND #{connection.quote(value.end)}"
end
else
if round
where_part = " WHERE round(COALESCE(average,0), #{precision.to_i}) = #{connection.quote(value)}"
else
where_part = " WHERE COALESCE(average,0) = #{connection.quote(value)}"
end
end
find_by_sql base_sql + where_part
end
end
end
end
end
end
ActiveRecord::Base.send :include, ActiveRecord::Acts::Rated
|
substancelab/acts-as-rated
|
lib/acts-as-rated.rb
|
require "acts-as-rated/acts_as_rated"
|
substancelab/acts-as-rated
|
test/dummy_classes.rb
|
<reponame>substancelab/acts-as-rated
class User < ActiveRecord::Base
end
class Worker < ActiveRecord::Base
set_table_name 'users'
end
class Movie < ActiveRecord::Base
acts_as_rated
end
class Film < ActiveRecord::Base
set_table_name 'movies'
acts_as_rated :rating_range => 1..5
end
class Book < ActiveRecord::Base
acts_as_rated :rater_class => 'Worker'
end
class NoRaterRating < ActiveRecord::Base
belongs_to :rated, :polymorphic => true
end
class StatsRating < ActiveRecord::Base
belongs_to :rated, :polymorphic => true
belongs_to :rater, :class_name => 'User', :foreign_key => :rater_id
end
class MyStatsRating < ActiveRecord::Base
belongs_to :rated, :polymorphic => true
belongs_to :rater, :class_name => 'User', :foreign_key => :rater_id
end
class Car < ActiveRecord::Base
acts_as_rated :rating_class => 'NoRaterRating', :no_rater => true
end
class Mechanic < ActiveRecord::Base
set_table_name 'users'
end
class Truck < ActiveRecord::Base
set_table_name 'cars'
acts_as_rated :rating_class => 'NoRaterRating', :no_rater => true, :rater_class => 'Mechanic'
end
class Video < ActiveRecord::Base
acts_as_rated :with_stats_table => true, :rating_class => 'StatsRating'
end
class MyStatistic < ActiveRecord::Base
belongs_to :rated, :polymorphic => true
end
class Tape < ActiveRecord::Base
set_table_name 'videos'
acts_as_rated :with_stats_table => true, :stats_class => 'MyStatistic', :rating_class => 'MyStatsRating'
end
|
substancelab/acts-as-rated
|
lib/acts-as-rated/version.rb
|
module Acts
module As
module Rated
VERSION = "0.0.5"
end
end
end
|
substancelab/acts-as-rated
|
test/migration_test.rb
|
ENV['NO_SCHEMA_LOAD'] = 'true'
require File.join(File.dirname(__FILE__), 'abstract_unit')
require File.join(File.dirname(__FILE__), 'dummy_classes')
if ActiveRecord::Base.connection.supports_migrations?
class MigrationTest < Test::Unit::TestCase
self.use_transactional_fixtures = false
# Defeat table creation!
def create_fixtures(*table_names)
end
def setup
teardown # Same in our case...
end
def teardown
ActiveRecord::Base.connection.initialize_schema_information
ActiveRecord::Base.connection.update "UPDATE schema_info SET version = 0"
[Movie, Book, Car, NoRaterRating, Rating, User, Video, RatingStatistic, MyStatistic, StatsRating, MyStatsRating].each do |c|
c.connection.drop_table c.table_name rescue nil
c.reset_column_information
end
end
# Add ratings table AND add the special stats table
def test_add_ratings_table_migration
verify_tables_do_not_exist
# up we go...
ActiveRecord::Migrator.up(File.dirname(__FILE__) + '/fixtures/migrations/')
[Book, Movie, Car, Video, Truck, Tape, Film, User, Mechanic].each do |c|
t = nil
assert_nothing_raised { t = c.create }
assert_respond_to t, :title
assert_respond_to t, :rating_average unless [User, Mechanic].include?(c)
assert t.attributes.include?('rating_avg') unless [User, Mechanic, Book, Video, Tape].include?(c)
assert !t.attributes.include?('rating_avg') if [User, Mechanic, Book, Video, Tape].include?(c)
end
r = nil
assert_nothing_raised { r = Rating.create }
assert_respond_to r, :rater_id
n = nil
assert_nothing_raised { n = NoRaterRating.create }
assert_raises(NoMethodError) { n.rater_id }
assert_respond_to n, :rating
s = nil
assert_nothing_raised { s = RatingStatistic.create }
assert_respond_to s, :rated_id
assert_respond_to s, :rated_type
assert_respond_to s, :rating_avg
m = nil
assert_nothing_raised { m = MyStatistic.create }
assert_respond_to m, :rated_id
assert_respond_to m, :rated_type
assert_respond_to m, :rating_avg
# down again
ActiveRecord::Migrator.down(File.dirname(__FILE__) + '/fixtures/migrations/')
verify_tables_do_not_exist
end
def verify_tables_do_not_exist
[Book, Movie, Car, User, Rating, Video, NoRaterRating, RatingStatistic, MyStatistic, StatsRating, MyStatsRating].each do |c|
assert_raises(ActiveRecord::StatementInvalid) { c.create }
end
end
end
end
|
substancelab/acts-as-rated
|
test/rated_test.rb
|
<reponame>substancelab/acts-as-rated<gh_stars>1-10
require File.join(File.dirname(__FILE__), 'abstract_unit')
require File.join(File.dirname(__FILE__), 'dummy_classes')
class RatedTest < Test::Unit::TestCase
fixtures :cars, :movies, :books, :users, :ratings, :no_rater_ratings, :videos, :stats_ratings, :my_stats_ratings, :rating_statistics, :my_statistics
def test_rate
# Regular one...
m = movies(:gone_with_the_wind)
check_average m, 4.33
m.rate 1, users(:sarah)
check_average m, 3
m = Movie.new :title => 'King Kong'
m.rate 4, users(:john)
assert m.new_record?
assert_equal 4, m.rating_average
assert_equal 1, m.rating_count
assert_equal 4, m.rating_total
assert m.save
m = Movie.find m.id
assert_equal 4, m.rating_average
assert_equal 1, m.rating_count
assert_equal 4, m.rating_total
m.rate 6, users(:bill)
m.rate 2, users(:sarah)
assert_equal 4, m.rating_average
assert_equal 3, m.rating_count
assert_equal 12, m.rating_total
assert_raise(ActiveRecord::Acts::Rated::RateError) { m.rate 6 }
# Ratring with norating columns
b = books(:shogun)
assert_raise(NoMethodError) { b.rating_total }
check_average b, 3.75
b.rate 10, Worker.find(users(:jane).id)
check_average b, 5.5
# Rating with no rater
c = cars(:bug)
check_average c, 4
assert_raise(ActiveRecord::Acts::Rated::RateError) { c.rate 10, users(:jill) }
c.rate 10
c.rate 10
c.rate 10
c.rate 10
c.rate 10
check_average c, 9
# Ranged ratings
f = Film.find :first, :order => 'title'
assert_equal 'Crash', f.title
assert_raise(ActiveRecord::Acts::Rated::RateError) { f.rate 0, users(:sarah) }
assert_raise(ActiveRecord::Acts::Rated::RateError) { f.rate 5.0001, users(:sarah) }
f.rate 1, users(:sarah)
f.rate 5, users(:jane)
check_average f, 3
# rating with an external statistics table
v = videos(:ten)
rc = v.ratings.count
assert_raise(NoMethodError) { v.rating_total }
check_average v, 1
v.rate 9, users(:jane)
check_average v, 3
assert_equal rc, v.ratings.count
v.rate 3, users(:jack)
check_average v, 3
assert_equal rc + 1, v.ratings.count
t = Tape.find(videos(:fame).id)
rc = t.ratings.count
assert_raise(NoMethodError) { t.rating_total }
check_average t, 5
t.rate 2, users(:jane)
check_average t, 4
assert_equal rc, t.ratings.count
t.rate 8, users(:jack)
check_average t, 5
assert_equal rc + 1, t.ratings.count
v = Video.new :title => 'Hair'
v.save
check_average v, 0
v.rate 4, users(:bill)
check_average v, 4
t = Tape.new :title => 'Friends'
t.save
check_average t, 0
t.rate 4, users(:bill)
check_average t, 4
t.rate 6, users(:jill)
check_average t, 5
# Rating with the wrong rater class or one that's not initialized
assert_raise(ActiveRecord::Acts::Rated::RateError) { b.rate 10, users(:jane) }
assert_raise(ActiveRecord::Acts::Rated::RateError) { b.rate 10, 3 }
assert_raise(ActiveRecord::Acts::Rated::RateError) { b.rate 10, Worker.new }
assert_raise(ActiveRecord::Acts::Rated::RateError) { b.rate 10 }
end
def test_unrate
# Regular one...
m = movies(:gone_with_the_wind)
check_average m, 4.33
assert_raise(ActiveRecord::Acts::Rated::RateError) { m.unrate nil }
m.unrate users(:john)
m.unrate users(:bill)
m.unrate users(:sarah)
m.unrate users(:jane)
m.unrate users(:jill)
check_average m, 0
m = Movie.new :title => 'King Kong'
m.rate 4, users(:john)
m.rate 4, users(:bill)
assert m.new_record?
assert_equal 4, m.rating_average
assert_equal 2, m.rating_count
assert_equal 8, m.rating_total
assert m.save
m = Movie.find m.id
assert_equal 4, m.rating_average
assert_equal 2, m.rating_count
assert_equal 8, m.rating_total
m.unrate users(:john)
assert_equal 4, m.rating_average
assert_equal 1, m.rating_count
assert_equal 4, m.rating_total
# Unrating with norating columns
b = books(:shogun)
assert_raise(NoMethodError) { b.ratings[0].rating_total }
check_average b, 3.75
b.unrate Worker.find(users(:bill).id)
check_average b, 4
# Unrating with external stats table
v = videos(:fields_of_dreams)
check_average v, 3.2
assert_raise(ActiveRecord::Acts::Rated::RateError) { v.unrate nil }
v.unrate users(:john)
v.unrate users(:bill)
v.unrate users(:sarah)
v.unrate users(:jane)
v.unrate users(:jill)
check_average v, 0
v = Video.new :title => 'King Kong'
assert v.new_record?
assert v.save
v = Video.find v.id
v.rate 4, users(:john)
v.rate 4, users(:bill)
assert_equal 4, v.rating_average
assert_equal 2, v.rated_count
assert_equal 8, v.rated_total
v.unrate users(:john)
assert_equal 4, v.rating_average
assert_equal 1, v.rated_count
assert_equal 4, v.rated_total
t = Tape.find(videos(:fields_of_dreams).id)
check_average t, 3.2
assert_raise(ActiveRecord::Acts::Rated::RateError) { t.unrate nil }
t.unrate users(:john)
t.unrate users(:bill)
t.unrate users(:sarah)
t.unrate users(:jane)
t.unrate users(:jill)
check_average t, 0
t = Tape.new :title => 'Scream'
assert t.save
t.rate 4, users(:john)
t.rate 6, users(:bill)
t = Tape.find t.id
assert_equal 5, t.rating_average
assert_equal 2, t.rated_count
assert_equal 10, t.rated_total
t.unrate users(:john)
assert_equal 6, t.rating_average
assert_equal 1, t.rated_count
assert_equal 6, t.rated_total
# No unrating with no rater
c = cars(:bug)
assert_raise(ActiveRecord::Acts::Rated::RateError) { c.unrate users(:jill) }
assert_raise(ActiveRecord::Acts::Rated::RateError) { c.unrate nil }
# Check unrater validity
b = books(:shogun)
assert_raise(ActiveRecord::Acts::Rated::RateError) { b.unrate users(:jane) }
assert_raise(ActiveRecord::Acts::Rated::RateError) { b.unrate 3 }
assert_raise(ActiveRecord::Acts::Rated::RateError) { b.unrate Worker.new }
end
def test_rated?
[Car, Movie, Book, Video, Tape, Truck, Film].each do |c|
# First check all the ones we have in the fixtures
c.find(:all).each do |o|
assert o.rated? if o.rated_count > 0
end
# Then create some new ones and test those as well
o = c.new(:title => 'Test Title')
assert o.save
assert !o.rated?
o.rate 4, Worker.find(users(:john).id) if [Book].include? c
o.rate 4, users(:john) if [Movie, Video, Tape, Film].include? c
o.rate 4 if [Car, Truck].include? c
#o.reload
assert o.rated?
end
end
def test_rating_average
m = movies(:gone_with_the_wind)
check_average m, 4.33
m = movies(:oz)
check_average m, 5
m = movies(:crash)
check_average m, 0
m.rate 3, users(:john)
m.rate 5, users(:bill)
check_average m, 4
m.rate 3, users(:bill)
check_average m, 3
m.unrate users(:bill)
check_average m, 3
c = cars(:camry)
check_average c, 3
c = cars(:bug)
check_average c, 4
c = cars(:expedition)
check_average c, 0
c.rate 3
c.rate 5
check_average c, 4
c.rate 3
check_average c, 3.66
end
def test_count
m = movies(:gone_with_the_wind)
assert_equal 3, m.rated_count
m.rate 4, users(:john)
m.rate 4, users(:bill)
m.rate 4, users(:sarah)
m.rate 4, users(:jane)
m.rate 4, users(:jill)
assert_equal 5, m.rated_count
c = cars(:expedition)
assert_equal 0, c.rated_count
c.rate 4
c.rate 4
c.rate 4
c.rate 4
c.rate 4
assert_equal 5, c.rated_count
b = books(:animal_farm)
assert_equal 4, b.rated_count
b.rate 4, Worker.find(users(:john).id)
b.rate 4, Worker.find(users(:bill).id)
b.rate 4, Worker.find(users(:sarah).id)
b.rate 4, Worker.find(users(:jane).id)
b.rate 4, Worker.find(users(:jill).id)
assert_equal 5, b.rated_count
end
def test_total
m = movies(:gone_with_the_wind)
assert_equal 13, m.rated_total
m.rate 4, users(:john)
m.rate 4, users(:bill)
m.rate 4, users(:sarah)
m.rate 4, users(:jane)
m.rate 4, users(:jill)
assert_equal 20, m.rated_total
c = cars(:expedition)
assert_equal 0, c.rated_total
c.rate 4
c.rate 4
c.rate 4
c.rate 4
c.rate 4
assert_equal 20, c.rated_total
b = books(:animal_farm)
assert_equal 12, b.rated_total
b.rate 4, Worker.find(users(:john).id)
b.rate 4, Worker.find(users(:bill).id)
b.rate 4, Worker.find(users(:sarah).id)
b.rate 4, Worker.find(users(:jane).id)
b.rate 4, Worker.find(users(:jill).id)
assert_equal 20, b.rated_total
end
def test_rated_by?
m = movies(:gone_with_the_wind)
m.rate 4, users(:john)
m.rate 4, users(:bill)
m.rate 4, users(:sarah)
m.rate 4, users(:jane)
m.rate 4, users(:jill)
m.unrate users(:jill)
m.unrate users(:sarah)
assert m.rated_by?(users(:john))
assert m.rated_by?(users(:bill))
assert m.rated_by?(users(:jane))
assert !m.rated_by?(users(:jill))
assert !m.rated_by?(users(:sarah))
b = books(:animal_farm)
b.rate 4, Worker.find(users(:john).id)
b.rate 4, Worker.find(users(:bill).id)
b.rate 4, Worker.find(users(:sarah).id)
b.rate 4, Worker.find(users(:jane).id)
b.rate 4, Worker.find(users(:jill).id)
b.unrate Worker.find(users(:john).id)
b.unrate Worker.find(users(:bill).id)
assert !b.rated_by?(Worker.find(users(:john).id) )
assert !b.rated_by?(Worker.find(users(:bill).id) )
assert b.rated_by?(Worker.find(users(:sarah).id))
assert b.rated_by?(Worker.find(users(:jane).id) )
assert b.rated_by?(Worker.find(users(:jill).id) )
end
def test_find_by_rating
cs = Car.find_by_rating 0
assert_equal 1, cs.size
assert_equal 'Ford Expedition', cs[0].title
cs = Car.find_by_rating 3
assert_equal 1, cs.size
assert_equal '<NAME>', cs[0].title
cs = Car.find_by_rating 3.5
assert_equal 1, cs.size
assert_equal 'VW Golf', cs[0].title
cs = Car.find_by_rating 4, 0
check_returned_array cs, ['VW Golf', 'Carrera', 'VW Bug']
cs = Car.find_by_rating 3..4, 0
check_returned_array cs, ['<NAME>', 'VW Golf', 'Carrera', 'VW Bug']
cs = Car.find_by_rating 3..4
check_returned_array cs, ['<NAME>', 'VW Golf', 'VW Bug']
fs = Film.find_by_rating 1..4, 0
check_returned_array fs, ["Rambo 3", "Gone With The Wind", "Phantom Menace"]
cs = Car.find_by_rating 3..4, 0, false
check_returned_array cs, ['<NAME>', 'VW Golf', 'VW Bug']
cs = Car.find_by_rating 3..4.5, 0, false
check_returned_array cs, ['<NAME>', 'VW Golf', 'Carrera', 'VW Bug']
fs = Film.find_by_rating 1..4, 0, false
check_returned_array fs, ["Rambo 3", "Phantom Menace"]
ms = Movie.find_by_rating 5
check_returned_array ms, ["The Wizard of Oz"]
bs = Book.find_by_rating 3..3.7
check_returned_array bs, ["Alice in Wonderland", "Aminal Farm", "The Lord of the Rings", "Catch 22"]
bs = Book.find_by_rating 3..3.7, 0
check_returned_array bs, ["Alice in Wonderland", "Aminal Farm", "The Lord of the Rings"]
bs = Book.find_by_rating 1..3, 0
check_returned_array bs, ["Alice in Wonderland", "Aminal Farm", "The Lord of the Rings"]
bs = Book.find_by_rating 3, 0
check_returned_array bs, ["Alice in Wonderland", "Aminal Farm", "The Lord of the Rings"]
bs = Book.find_by_rating 3..3.7, 0, false
check_returned_array bs, ["Alice in Wonderland", "Aminal Farm", "The Lord of the Rings", "Catch 22"]
bs = Book.find_by_rating 1..3.3, 0, false
check_returned_array bs, ["Alice in Wonderland", "Aminal Farm", "The Lord of the Rings"]
bs = Book.find_by_rating 3.75, 0, false
check_returned_array bs, ["Shogun"]
end
def test_find_rated_by
assert_raise(ActiveRecord::Acts::Rated::RateError) { Car.find_rated_by 5 }
assert_raise(ActiveRecord::Acts::Rated::RateError) { Movie.find_rated_by nil }
assert_raise(ActiveRecord::Acts::Rated::RateError) { Movie.find_rated_by 1 }
ms = Movie.find_rated_by users(:john)
check_returned_array ms, ["Gone With The Wind", "The Wizard of Oz", "Phantom Menace", "Rambo 3"]
ms = Movie.find_rated_by users(:jack)
check_returned_array ms, []
m = Movie.new :title => 'Borat'
m.save
m.rate 5, users(:jack)
ms = Movie.find_rated_by users(:jack)
check_returned_array ms, ["Borat"]
bs = Book.find_rated_by Worker.find(users(:john).id)
check_returned_array bs, ["The Lord of the Rings", "Alice in Wonderland", "Catch 22", "Aminal Farm"]
fs = Film.find_rated_by users(:john)
check_returned_array fs, ["Gone With The Wind", "Phantom Menace", "The Wizard of Oz", "Rambo 3"]
f = Film.new :title => 'Kill Bill'
f.save
f.rate 4, users(:jill)
fs = Film.find_rated_by users(:jill)
check_returned_array fs, ["Rambo 3", "Phantom Menace", "Kill Bill"]
end
def test_associations
assert User.new.respond_to?(:ratings)
assert !Mechanic.new.respond_to?(:ratings)
assert Book.new.respond_to?(:ratings)
assert Book.new.respond_to?(:raters)
assert Car.new.respond_to?(:ratings)
assert !Car.new.respond_to?(:raters)
assert Truck.new.respond_to?(:ratings)
assert !Truck.new.respond_to?(:raters)
end
# This just test that the fixtures data makes sense
def test_all_fixtures
[Car, Movie, Book, Video, Tape, Truck, Film].each do |c|
c.find(:all).each do |o|
check_average o, o.rating_average
end
end
end
def check_average obj, value
assert_equal (value * 100).to_i, (obj.rating_average * 100).to_i
assert_equal (obj.ratings.average(:rating) * 100).to_i, (obj.rating_average * 100).to_i
end
def check_returned_array ar, expected_list
names = ar.collect {|e| e.title }
assert_equal expected_list.size, names.size
assert_equal [], names - expected_list
end
end
|
substancelab/acts-as-rated
|
acts-as-rated.gemspec
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/acts-as-rated/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["<NAME>"]
gem.email = ["<EMAIL>"]
gem.description = %q{Flexible, configurable, and easy to use with the defaults. Supports 3 different ways to manage rating statistics.}
gem.summary = %q{Rails plugin rating system for ActiveRecord models.}
gem.homepage = 'https://github.com/jasherai/acts-as-rated'
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "acts-as-rated"
gem.require_paths = ['lib']
gem.version = Acts::As::Rated::VERSION
end
|
dalen/puppet-puppetdbquery
|
spec/functions/query_nodes_spec.rb
|
#! /usr/bin/env ruby -S rspec
require 'spec_helper'
require 'puppetdb/connection'
describe 'query_nodes' do
context 'without fact parameter' do
it do
PuppetDB::Connection.any_instance.expects(:query)
.with(:nodes, ['in', 'certname', ['extract', 'certname', ['select_fact_contents', ['and', ['=', 'path', ['hostname']], ['=', 'value', 'apache4']]]]], :extract => :certname)
.returns [ { 'certname' => 'apache4.puppetexplorer.io' } ]
should run.with_params('hostname="apache4"').and_return(['apache4.puppetexplorer.io'])
end
end
context 'with a fact parameter' do
it do
PuppetDB::Connection.any_instance.expects(:query)
.with(:facts, ['and', ['in', 'certname', ['extract', 'certname', ['select_fact_contents', ['and', ['=', 'path', ['hostname']], ['=', 'value', 'apache4']]]]], ['or', ['=', 'name', 'ipaddress']]], :extract => :value)
.returns [ { 'value' => '172.31.6.80' } ]
should run.with_params('hostname="apache4"', 'ipaddress').and_return(['172.31.6.80'])
end
end
context 'with a nested fact parameter' do
it do
PuppetDB::Connection.any_instance.expects(:query)
.with(:facts, ['and', ['in', 'certname', ['extract', 'certname', ['select_fact_contents', ['and', ['=', 'path', ['hostname']], ['=', 'value', 'apache4']]]]], ['or', ['=', 'name', 'networking']]], :extract => :value)
.returns [
{
'value' => {
'interfaces' => {
'eth0' => {
'ip' => '172.31.6.80',
'network' => '172.31.0.0',
},
'eth1' => {
'ip' => '172.16.58.3',
'network' => '192.168.3.11',
},
'bond0' => {},
}
}
}
]
should run.with_params('hostname="apache4"', 'networking.interfaces.eth1.ip').and_return(['172.16.58.3'])
end
end
context 'with a missing nested fact parameter' do
it do
PuppetDB::Connection.any_instance.expects(:query)
.with(:facts, ['and', ['in', 'certname', ['extract', 'certname', ['select_fact_contents', ['and', ['=', 'path', ['hostname']], ['=', 'value', 'apache4']]]]], ['or', ['=', 'name', 'networking']]], :extract => :value)
.returns [
{
'value' => {
'interfaces' => {
'eth0' => {
'ip' => '172.31.6.80',
'network' => '172.31.0.0',
},
'eth1' => {
'ip' => '172.16.58.3',
'network' => '192.168.3.11',
},
'bond0' => {},
}
}
}
]
should run.with_params('hostname="apache4"', 'networking.interfaces.missing_interface.ip').and_return([nil])
end
end
end
|
dalen/puppet-puppetdbquery
|
lib/puppet/application/puppetdbquery.rb
|
<reponame>dalen/puppet-puppetdbquery
require 'puppet/application/face_base'
class Puppet::Application::Puppetdbquery < Puppet::Application::FaceBase
def self.setting
use_ssl = true
begin
require 'puppet'
require 'puppet/util/puppetdb'
PuppetDB::Connection.check_version
uri = URI(Puppet::Util::Puppetdb.config.server_urls.first)
host = uri.host
port = uri.port
rescue Exception => e
Puppet.debug(e.message)
host = 'puppetdb'
port = 8081
end
Puppet.debug(host)
Puppet.debug(port)
Puppet.debug("use_ssl=#{use_ssl}")
{ :host => host,
:port => port,
:use_ssl => use_ssl
}
end
end
|
dalen/puppet-puppetdbquery
|
spec/functions/query_facts_spec.rb
|
<reponame>dalen/puppet-puppetdbquery<filename>spec/functions/query_facts_spec.rb
#! /usr/bin/env ruby -S rspec
require 'spec_helper'
require 'puppetdb/connection'
describe 'query_facts' do
it do
PuppetDB::Connection.any_instance.expects(:query)
.with(:facts, ['or', ['=', 'name', 'ipaddress']], {:extract => [:certname, :name, :value]})
.returns [
{ 'certname' => 'apache4.puppetexplorer.io', 'environment' => 'production', 'name' => 'ipaddress', 'value' => '172.31.6.80' }
]
should run.with_params('', ['ipaddress']).and_return('apache4.puppetexplorer.io' => { 'ipaddress' => '172.31.6.80' })
end
it do
PuppetDB::Connection.any_instance.expects(:query)
.with(:facts, ['or', ['=', 'name', 'ipaddress'], ['=', 'name', 'network_eth0']], {:extract => [:certname, :name, :value]})
.returns [
{ 'certname' => 'apache4.puppetexplorer.io', 'environment' => 'production', 'name' => 'ipaddress', 'value' => '172.31.6.80' },
{ 'certname' => 'apache4.puppetexplorer.io', 'environment' => 'production', 'name' => 'network_eth0', 'value' => '172.31.0.0' }
]
should run.with_params('', ['ipaddress', 'network_eth0']).and_return('apache4.puppetexplorer.io' => { 'ipaddress' => '172.31.6.80', 'network_eth0' => '172.31.0.0' })
end
context 'with a nested fact parameter' do
it do
PuppetDB::Connection.any_instance.expects(:query)
.with(:facts, ['or', ['=', 'name', 'ipaddress'], ['=', 'name', 'networking']], {:extract => [:certname, :name, :value]})
.returns [
{ 'certname' => 'apache4.puppetexplorer.io', 'environment' => 'production', 'name' => 'ipaddress', 'value' => '172.31.6.80' },
{
'certname' => 'apache4.puppetexplorer.io',
'environment' => 'production',
'name' => 'networking',
'value' => {
'interfaces' => {
'eth0' => {
'ip' => '172.31.6.80',
'network' => '172.31.0.0',
},
'eth1' => {
'ip' => '172.16.17.32',
'network' => '172.16.31.10',
},
'bond0' => {},
}
}
}
]
should run.with_params('', ['ipaddress', 'networking.interfaces.eth0.ip']).and_return('apache4.puppetexplorer.io' => { 'ipaddress' => '172.31.6.80', 'networking_interfaces_eth0_ip' => '172.31.6.80' })
end
end
end
|
dalen/puppet-puppetdbquery
|
lib/puppetdb.rb
|
<reponame>dalen/puppet-puppetdbquery
module PuppetDB
# Current version of this module
VERSION ||= [3, 0, 1].freeze
end
|
dalen/puppet-puppetdbquery
|
lib/puppet/functions/query_facts.rb
|
# Accepts two arguments, a query used to discover nodes, and a list of facts
# that should be returned from those hosts.
#
# The query specified should conform to the following format:
# (Type[title] and fact_name<operator>fact_value) or ...
# Package[mysql-server] and cluster_id=my_first_cluster
#
# The facts list provided should be an array of fact names.
#
# The result is a hash that maps the name of the nodes to a hash of facts that
# contains the facts specified.
Puppet::Functions.create_function('query_facts') do
require 'puppet/util/puppetdb'
# This is needed if the puppetdb library isn't pluginsynced to the master
$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
begin
require 'puppetdb/connection'
ensure
$LOAD_PATH.shift
end
dispatch :query_facts do
param 'Variant[String, Array]', :query
param 'Array[String, 1]', :facts
end
def query_facts(query, facts)
facts = facts.map { |fact| fact.match(/\./) ? fact.split('.') : fact }
facts_for_query = facts.map { |fact| fact.is_a?(Array) ? fact.first : fact }
uri = URI(Puppet::Util::Puppetdb.config.server_urls.first)
puppetdb = PuppetDB::Connection.new(uri.host, uri.port, uri.scheme == 'https')
parser = PuppetDB::Parser.new
query = parser.facts_query query, facts_for_query if query.is_a? String
parser.facts_hash(puppetdb.query(:facts, query, :extract => [:certname, :name, :value]), facts)
end
end
|
dalen/puppet-puppetdbquery
|
lib/puppetdb/parser_helper.rb
|
<gh_stars>10-100
# Helper methods for the parser, included in the parser class
require 'puppetdb'
module PuppetDB::ParserHelper
# Parse a query string into a PuppetDB query
#
# @param query [String] the query string to parse
# @param endpoint [Symbol] the endpoint for which the query should be evaluated
# @return [Array] the PuppetDB query
def parse(query, endpoint = :nodes)
if query = scan_str(query)
query.optimize.evaluate [endpoint]
end
end
# Create a query for facts on nodes matching a query string
#
# @param query [String] the query string to parse
# @param facts [Array] an array of facts to get
# @return [Array] the PuppetDB query
def facts_query(query, facts = nil)
nodequery = parse(query, :facts)
if facts.nil?
nodequery
else
factquery = ['or', *facts.collect { |f|
if (f =~ /^\/(.+)\/$/)
['~', 'name', f.scan(/^\/(.+)\/$/).last.first]
else
['=', 'name', f]
end
}]
if nodequery
['and', nodequery, factquery]
else
factquery
end
end
end
# Turn an array of facts into a hash of nodes containing facts
#
# @param fact_hash [Array] fact values
# @param facts [Array] fact names
# @return [Hash] nodes as keys containing a hash of facts as value
def facts_hash(fact_hash, facts)
fact_hash.reduce({}) do |ret, fact|
# Array#include? only matches on values of the same type, so if we find
# a matching string, it's not a nested query.
name, value = if facts.include?(fact['name']) || facts == [:all] ||
# in case a regex pattern is used in the facts query
facts.index{ |factname| factname =~ /^\/(.+)\/$/ && Regexp.new(factname.match(/^\/(.+)\/$/)[1]).match(fact['name']) }
[fact['name'], fact['value']]
else
# Find the set of keys where the first value is the fact name
nested_keys = facts.select do |x|
x.is_a?(Array) && x.first == fact['name']
end.flatten
# Join all the key names together with an underscore to give
# us a unique name, and then send all the keys but the fact
# name (which was already queried out) to extract_nested_fact
[
nested_keys.join("_"),
extract_nested_fact([fact], nested_keys[1..-1]).first
]
end
if ret.include? fact['certname']
ret[fact['certname']][name] = value
else
ret[fact['certname']] = { name => value }
end
ret
end
end
# Take an array of hashes of fact hashes and get a nested value from each
# of them.
#
# @param fact_hashes [Array] an array of hashes of fact hashes
# @param keys [Array] an array of keys to dig into the hash
# @returt [Array] an array of extracted values
def extract_nested_fact(fact_hashes, keys)
fact_hashes.map do |fact_hash|
hash = fact_hash['value']
# Traverse the hash, setting `hash` equal to the next level deep each step
keys[0..-2].each do |key|
hash = hash.fetch(key, {})
end
# Lookup the final key. This will convert to nil if we've been defaulting
# to empty hash beforehand.
hash[keys.last]
end
end
# Turn a query into one for only certain fields
def self.extract(*field, query)
['extract', field.collect(&:to_s), query]
end
end
|
dalen/puppet-puppetdbquery
|
lib/puppet/functions/puppetdb_lookup_key.rb
|
# The `puppetdb_lookup_key` is a hiera 5 `lookup_key` data provider function.
# See (https://docs.puppet.com/puppet/latest/hiera_custom_lookup_key.html) for
# more info.
#
# See README.md#hiera-backend for usage.
#
Puppet::Functions.create_function(:puppetdb_lookup_key) do
dispatch :puppetdb_lookup_key do
param 'String[1]', :key
param 'Hash[String[1],Any]', :options
param 'Puppet::LookupContext', :context
end
def puppetdb_lookup_key(key, options, context)
return context.cached_value(key) if context.cache_has_key(key)
if !key.end_with?('::_nodequery') && nodequery = call_function('lookup', "#{key}::_nodequery", 'merge' => 'first', 'default_value' => nil)
# Support specifying the query in a few different ways
query, fact, sort = case nodequery
when Hash then [nodequery['query'], nodequery['fact'], nodequery['sort']]
when Array then nodequery
else [nodequery.to_s, nil, nil]
end
paramz = [query, fact].compact
result = call_function('query_nodes', *paramz)
result.sort! if sort
context.cache(key, result)
else
context.not_found
end
end
end
|
dalen/puppet-puppetdbquery
|
lib/puppet/functions/query_nodes.rb
|
# Accepts two arguments, a query used to discover nodes, and an optional
# fact that should be returned.
#
# The query specified should conform to the following format:
# (Type[title] and fact_name<operator>fact_value) or ...
# Package["mysql-server"] and cluster_id=my_first_cluster
#
# The second argument should be single fact or series of keys joined on periods
# (this argument is optional)
Puppet::Functions.create_function('query_nodes') do
require 'puppet/util/puppetdb'
# This is needed if the puppetdb library isn't pluginsynced to the master
$LOAD_PATH.unshift File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
begin
require 'puppetdb/connection'
ensure
$LOAD_PATH.shift
end
dispatch :query_nodes do
param 'Variant[String, Array]', :query
end
dispatch :query_nodes_fact do
param 'Variant[String, Array]', :query
param 'String', :fact
end
def parser
@parser ||= PuppetDB::Parser.new
end
def puppetdb
@uri ||= URI(Puppet::Util::Puppetdb.config.server_urls.first)
@puppetdb ||= PuppetDB::Connection.new(
@uri.host,
@uri.port,
@uri.scheme == 'https'
)
end
def query_nodes(query)
query = parser.parse(query, :nodes) if query.is_a? String
puppetdb.query(:nodes, query, :extract => :certname).collect do |n|
n['certname']
end
end
def query_nodes_fact(query, fact)
fact_for_query = fact.split('.').first
query = parser.facts_query(query, [fact_for_query])
response = puppetdb.query(:facts, query, :extract => :value)
if fact.split('.').size > 1
parser.extract_nested_fact(response, fact.split('.')[1..-1])
else
response.collect { |f| f['value'] }
end
end
end
|
dalen/puppet-puppetdbquery
|
ruby-puppetdb.gemspec
|
<filename>ruby-puppetdb.gemspec
# -*- encoding: UTF-8
lib = File.expand_path('../lib/', __FILE__)
$LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib)
require 'puppetdb'
Gem::Specification.new do |s|
s.name = 'ruby-puppetdb'
s.version = PuppetDB::VERSION.join '.'
s.platform = Gem::Platform::RUBY
s.authors = ['<NAME>']
s.email = ['<EMAIL>']
s.homepage = 'https://github.com/dalen/puppet-puppetdbquery'
s.summary = 'Query functions for PuppetDB'
s.description = 'A higher level query language for PuppetDB.'
s.license = 'Apache v2'
s.files = Dir.glob('{bin,lib}/**/*')
s.test_files = Dir.glob('{test,spec,features,examples}/**/*')
s.executables = Dir.glob('bin/**/*').map { |f| File.basename f }
s.require_paths = ['lib']
s.add_dependency 'json'
s.add_dependency 'chronic'
s.add_dependency 'puppet', '>= 3.0.0', '< 6.0.0'
s.add_development_dependency 'rspec', '~> 3.5'
s.add_development_dependency 'rspec-expectations', '~> 3.5'
s.add_development_dependency 'rspec-puppet', '~> 2.4'
s.add_development_dependency 'rake', '~> 12.3'
s.add_development_dependency 'puppetlabs_spec_helper'
s.add_development_dependency 'racc', '~> 1.4'
s.add_development_dependency 'rexical', '~> 1.0'
s.add_development_dependency 'puppet-blacksmith', '~> 4.1'
end
|
manuelmorales/forwarding-dsl
|
lib/forwarding_dsl/getsetter.rb
|
module ForwardingDsl
module Getsetter
NOT_SET = Object.new
def self.included klass
klass.extend ClassMethods
end
module ClassMethods
def getsetter *names
names.each do |name|
define_method name do |value = NOT_SET|
if value == NOT_SET
instance_variable_get "@#{name}"
else
send "#{name}=", value
end
end
define_method "#{name}=" do |value|
instance_variable_set "@#{name}", value
end
end
end
end
end
end
|
manuelmorales/forwarding-dsl
|
spec/forwarding_dsl_spec.rb
|
require_relative 'spec_helper'
describe ForwardingDsl do
it 'has a version' do
expect(ForwardingDsl::VERSION).not_to be_nil
end
it 'delegates .run() to Dsl' do
target = double('target')
expect(target).to receive(:some_method)
ForwardingDsl.run target do
some_method
end
end
end
|
manuelmorales/forwarding-dsl
|
lib/forwarding_dsl.rb
|
require "forwarding_dsl/version"
module ForwardingDsl
autoload :Dsl, 'forwarding_dsl/dsl'
autoload :Getsetter, 'forwarding_dsl/getsetter'
def self.run *args, &block
Dsl.run *args, &block
end
end
|
manuelmorales/forwarding-dsl
|
lib/forwarding_dsl/dsl.rb
|
module ForwardingDsl
class Dsl
attr_accessor :this
attr_accessor :that
def self.run target, &block
return target unless block_given?
case block.arity
when 0 then
new(target, block.binding.eval('self')).
send(:instance_exec, &block)
when 1 then
block.call target
else
raise ArgumentError.new "Wrong number of arguments. Pass 1 or none."
end
end
def initialize this, that
@this = this
@that = that
end
def method_missing name, *args, &block
if this.respond_to? name
this.public_send name, *args, &block
else
that.public_send name, *args, &block
end
end
def respond_to_missing? name, *args
this.respond_to?(name, *args) ||
that.respond_to?(name, *args) ||
super
end
end
end
|
manuelmorales/forwarding-dsl
|
spec/forwarding_dsl/dsl_spec.rb
|
<reponame>manuelmorales/forwarding-dsl
require_relative '../spec_helper'
describe ForwardingDsl::Dsl do
let(:target_class) do
Class.new do
def a_method
end
private
def a_private_emthod
end
end
end
let(:target) { target_class.new }
let(:an_external_method) { :external_result }
describe '.run' do
subject{ ForwardingDsl::Dsl }
describe 'with no args' do
it 'forwards messages to the target' do
expect(target).to receive(:a_method).with(42)
subject.run target do
a_method 42
end
end
it 'responds_to? target methods' do
subject.run target do
expect(respond_to?(:a_method)).to be true
end
end
it 'hides private methods' do
expect do
subject.run target do
a_private_method
end
end.to raise_error(NoMethodError)
end
it 'allows calling methods from the outside' do
expect(target).to receive(:a_method).with :external_result
subject.run target do
a_method an_external_method
end
end
it 'responds_to? external methods' do
subject.run target do
expect(respond_to?(:an_external_method)).to be true
end
end
it 'allows using this' do
subject.run target do
expect(this).to be target
end
end
it 'allows using that' do
outer_context = self
subject.run target do
expect(that).to be outer_context
end
end
it 'allows nesting' do
stub_const 'Owner', Class.new
Owner.class_eval do
include ForwardingDsl::Getsetter
getsetter :name
end
stub_const 'Folder', Class.new
Folder.class_eval do
include ForwardingDsl::Getsetter
getsetter :name
def initialize &block
ForwardingDsl.run self, &block
end
def owner &block
@owner ||= Owner.new
ForwardingDsl.run @owner, &block
end
end
folder = Folder.new do
name 'Folder name'
end
expect(folder.name).to eq 'Folder name'
folder = Folder.new do
name 'Folder name'
owner do
name 'Owner name'
end
end
expect(folder.owner.name).to eq 'Owner name'
expect(folder.name).to eq 'Folder name'
end
end
describe 'with 1 arg' do
it 'forwards no messages to the target' do
expect(target).not_to receive(:a_method)
expect do
subject.run target do |t|
a_method 42
end
end.to raise_error(NoMethodError)
end
it 'yields the target' do
subject.run target do |t|
expect(t).to be target
end
end
it 'runs in the outer context' do
outer_context = self
subject.run target do |t|
expect(self).to be outer_context
end
end
end
describe 'with more args' do
it 'raises exception' do
expect(target).not_to receive(:a_method)
expect do
subject.run target do |t, x|
end
end.to raise_error(ArgumentError)
end
end
describe 'with no block' do
it 'returns the target' do
expect(subject.run target).to be target
end
end
describe 'with a zero arity lambda' do
it 'works normally' do
expect(target).to receive(:a_method)
block = lambda { a_method }
subject.run target, &block
end
end
it 'returns the result of the last line' do
expect(target).to receive(:a_method).and_return(:something)
expect(subject.run(target){ a_method }).to be :something
end
end
end
|
manuelmorales/forwarding-dsl
|
spec/forwarding_dsl/getsetter_spec.rb
|
<filename>spec/forwarding_dsl/getsetter_spec.rb
require_relative '../spec_helper'
RSpec.describe ForwardingDsl::Getsetter do
subject { subject_class.new }
let(:subject_class) { Class.new { include ForwardingDsl::Getsetter } }
describe 'getsetter()' do
it 'allows setting an attribute passing it as an argument' do
subject_class.class_eval do
getsetter :name
end
subject.name 'Test'
expect(subject.name).to eq 'Test'
end
it 'allows setting an attribute by equality' do
subject_class.class_eval do
getsetter :name
end
subject.name = 'Test'
expect(subject.name).to eq 'Test'
end
it 'allows passing several names' do
subject_class.class_eval do
getsetter :name, :surname
end
subject.surname 'Test'
expect(subject.surname).to eq 'Test'
end
it 'allows overriding the name= method' do
subject_class.class_eval do
getsetter :name
end
expect(subject).to receive(:name=).with 'Test'
subject.name 'Test'
end
end
end
|
manuelmorales/forwarding-dsl
|
forwarding_dsl.gemspec
|
# coding: utf-8
gem_name = "forwarding_dsl" # TODO: Rename this
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "#{gem_name}/version"
Gem::Specification.new do |spec|
spec.name = gem_name
spec.version = ForwardingDsl::VERSION
spec.authors = ["<NAME>"]
spec.email = ['<EMAIL>']
spec.description = File.read('README.md').split("\n").reject{|l| l.length == 0 || l =~ /^[#=]+/ }.first
spec.summary = spec.description
spec.homepage = "https://github.com/manuelmorales/#{spec.name.gsub('_','-')}"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
|
teemutammela/contentful-middleman-dynamic-pages
|
config.rb
|
require "contentful"
require "rich_text_renderer"
require "redcarpet"
require "redcarpet/render_strip"
# Initialize Contentful Delivery API client.
client = Contentful::Client.new(
access_token: ENV["CONTENTFUL_DELIVERY_API_KEY"],
space: ENV["CONTENTFUL_SPACE_ID"]
)
helpers do
# Custom helper for converting Rich Text to HTML
def rich_text_to_html(value)
renderer = RichTextRenderer::Renderer.new
renderer.render(value)
end
# Custom helper for convert Markdown to HTML
def markdown_to_html(value)
renderer = Redcarpet::Markdown.new(
Redcarpet::Render::HTML,
autolink: false,
tables: true,
escape_html: false
)
renderer.render(value)
end
end
# Query entries that match the content type 'Page'.
# Parameter `include` is set to 0, since we don't need related entries.
# Parameter `limit` value set as 10 for development, 1000 for build.
pages = client.entries(
content_type: "page",
include: 0,
select: "fields.slug",
limit: build? ? 1000 : 10
)
# Map the 'Slug' field values of 'Page' entries into a flat array.
page_slugs = pages.map do |page|
page.fields[:slug]
end
# Query 'Pages' entry and set corresponding proxy.
page_slugs.each do |page_slug|
# Query 'Page' entry by 'Slug' field value.
page = client.entries(
content_type: "page",
include: 2,
"fields.slug": page_slug
).first
# Set proxy for 'Slug' field value and pass 'Page' entry's data to template.
proxy "/pages/#{page_slug}/index.html", "/pages/page.html", locals: {
page: page
}
end
# Ignore template on build
ignore "/pages/page.html"
# Activate and configure extensions.
# https://middlemanapp.com/advanced/configuration/#configuring-extensions
activate :autoprefixer do |prefix|
prefix.browsers = "last 2 versions"
end
|
tigrish/iso
|
spec/lib/iso/tag_spec.rb
|
<gh_stars>10-100
require 'spec_helper'
describe ISO::Tag do
describe ".new(code)" do
it "returns a tag containing the language and region" do
tag = ISO::Tag.new('en-MX')
expect(tag.language.code).to eq 'en'
expect(tag.region.code).to eq 'MX'
end
it "returns a tag containing the language and UN region" do
tag = ISO::Tag.new('en-419')
expect(tag.language.code).to eq 'en'
expect(tag.region.code).to eq '419'
end
it "returns a tag containing the language only" do
tag = ISO::Tag.new('en-XXXXXX')
expect(tag.language.code).to eq 'en'
expect(tag.region).to be_nil
end
it "returns a tag containing the region only" do
tag = ISO::Tag.new('gsw-CH')
expect(tag.language).to be_nil
expect(tag.region.code).to eq 'CH'
end
it "returns a tag containing the UN region only" do
tag = ISO::Tag.new('gsw-419')
expect(tag.language).to be_nil
expect(tag.region.code).to eq '419'
end
it "returns a tag containing no language or region" do
tag = ISO::Tag.new('csb-XXXXXX')
expect(tag.language).to be_nil
expect(tag.region).to be_nil
end
end
describe "#codes" do
it "returns an array containing each subtag's code" do
expect(ISO::Tag.new('en-US').codes).to eq %w(en US)
end
end
describe "#subtags" do
it "returns an array containing the language" do
tag = ISO::Tag.new('fr')
expect(tag.subtags.size).to eq 1
expect(tag.subtags.first).to be_kind_of(ISO::Language)
expect(tag.subtags.first.code).to eq 'fr'
end
it "returns an array containing the language and the region" do
tag = ISO::Tag.new('fr-CH')
expect(tag.subtags.size).to eq 2
expect(tag.subtags.first).to be_kind_of(ISO::Language)
expect(tag.subtags.first.code).to eq 'fr'
expect(tag.subtags.last).to be_kind_of(ISO::Region)
expect(tag.subtags.last.code).to eq 'CH'
end
end
describe "#valid?" do
it "returns true when a valid language is supplied" do
expect(ISO::Tag.new('da')).to be_valid
end
it "returns true when a valid language and region are supplied" do
expect(ISO::Tag.new('da-AT')).to be_valid
end
it "returns true when a valid language an UN region are supplied" do
expect(ISO::Tag.new('es-419')).to be_valid
end
it "returns false when no code is supplied" do
expect(ISO::Tag.new('')).to_not be_valid
end
it "returns false when supplied language is invalid" do
expect(ISO::Tag.new('lol')).to_not be_valid
end
it "returns false when supplied region is invalid" do
expect(ISO::Tag.new('en-lol')).to_not be_valid
end
end
end
|
tigrish/iso
|
iso.gemspec
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: iso 0.4.0 ruby lib
Gem::Specification.new do |s|
s.name = "iso".freeze
s.version = "0.4.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["<NAME>".freeze, "<NAME>".freeze]
s.date = "2020-11-17"
s.description = "A subset of the ISO spec implemented in ruby".freeze
s.email = "<EMAIL>".freeze
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
".rspec",
".travis.yml",
"Gemfile",
"Gemfile.lock",
"Guardfile",
"LICENSE.txt",
"README.md",
"Rakefile",
"VERSION",
"data/iso-3166-1.yml",
"data/iso-639-1.yml",
"data/un-m49.yml",
"iso.gemspec",
"lib/iso.rb",
"lib/iso/language.rb",
"lib/iso/region.rb",
"lib/iso/subtag.rb",
"lib/iso/tag.rb",
"lib/iso/un/region.rb",
"locales/en.yml",
"locales/fr.yml",
"spec/fixtures/base.yml",
"spec/lib/iso/language_spec.rb",
"spec/lib/iso/region_spec.rb",
"spec/lib/iso/subtag_spec.rb",
"spec/lib/iso/tag_spec.rb",
"spec/lib/iso/un/region_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = "http://github.com/tigrish/iso".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.0.3".freeze
s.summary = "A ruby implementation of ISO".freeze
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<i18n>.freeze, [">= 0"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.9"])
s.add_development_dependency(%q<rdoc>.freeze, ["~> 6.2"])
s.add_development_dependency(%q<bundler>.freeze, ["~> 2.0"])
s.add_development_dependency(%q<jeweler>.freeze, ["~> 2.3"])
s.add_development_dependency(%q<guard-rspec>.freeze, [">= 0"])
s.add_development_dependency(%q<localeapp>.freeze, [">= 0"])
else
s.add_dependency(%q<i18n>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.9"])
s.add_dependency(%q<rdoc>.freeze, ["~> 6.2"])
s.add_dependency(%q<bundler>.freeze, ["~> 2.0"])
s.add_dependency(%q<jeweler>.freeze, ["~> 2.3"])
s.add_dependency(%q<guard-rspec>.freeze, [">= 0"])
s.add_dependency(%q<localeapp>.freeze, [">= 0"])
end
else
s.add_dependency(%q<i18n>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.9"])
s.add_dependency(%q<rdoc>.freeze, ["~> 6.2"])
s.add_dependency(%q<bundler>.freeze, ["~> 2.0"])
s.add_dependency(%q<jeweler>.freeze, ["~> 2.3"])
s.add_dependency(%q<guard-rspec>.freeze, [">= 0"])
s.add_dependency(%q<localeapp>.freeze, [">= 0"])
end
end
|
tigrish/iso
|
spec/lib/iso/un/region_spec.rb
|
<reponame>tigrish/iso
require 'spec_helper'
describe ISO::UN::Region do
let(:has_iso) { ISO::UN::Region.find('004') }
let(:no_iso) { ISO::UN::Region.find('002') }
describe "#iso_code" do
it "returns the corresponding iso code" do
expect(has_iso.iso_code).to eq 'AF'
end
it "returns nil when there is no corresponding iso code" do
expect(no_iso.iso_code).to be_nil
end
end
describe "#name" do
it "uses the correct scope when there is an iso code" do
expect(has_iso.name).to eq 'Afghanistan'
end
it "uses the correct scope when there is no iso code" do
expect(no_iso.name).to eq 'Africa'
end
end
describe ".identify(full_code)" do
it "identifies from 'es-419'" do
region = ISO::UN::Region.identify('es-419')
expect(region).to_not be_nil
expect(region).to eq ISO::UN::Region.find('419')
end
it "returns nil when it can't identify" do
expect(ISO::UN::Region.identify('gsw')).to be_nil
end
end
end
|
tigrish/iso
|
spec/lib/iso/subtag_spec.rb
|
<gh_stars>10-100
require 'spec_helper'
class Subtag < ISO::Subtag
DEFINITIONS_FILE = "spec/fixtures/base.yml"
DEFAULT_CODE = "fr"
private
def i18n_scope
super << ".languages"
end
end
describe ISO::Subtag do
describe "#==(object)" do
it "returns true when both have the same code" do
expect(ISO::Region.find('SY')).to eq ISO::Region.find('SY')
end
it "returns false when they have different codes" do
expect(ISO::Region.find('FR')).to_not eq ISO::Region.find('GB')
end
end
describe "#name" do
let(:fake_region) { ISO::Subtag.new('FR', name: 'This is a lie') }
let(:mars) { ISO::Subtag.new('MRS') }
it 'will accept a name option' do
expect(I18n).to_not receive(:t)
expect(fake_region.name).to eq 'This is a lie'
end
it 'falls back to the translation' do
expect(I18n).to receive(:t).with('MRS', scope: 'vendor.iso').and_return('Mars')
expect(mars.name).to eq 'Mars'
end
end
describe "#full_name" do
it "is composed of the code and the name" do
full_name = Subtag.find('fr').full_name
expect(full_name).to match(/fr/)
expect(full_name).to match(/French/)
end
end
describe ".all" do
it "gets its definition from the DEFINITIONS_FILE" do
subtags = Subtag.all
expect(subtags[0]).to eq Subtag.find('en')
expect(subtags[1]).to eq Subtag.find('fr')
expect(subtags[2]).to eq Subtag.find('de')
end
end
describe ".find(code)" do
it "finds a subtag by code" do
subtag = Subtag.find('de')
expect(subtag.code).to eq 'de'
expect(subtag.name).to eq 'German'
end
it "returns nil when no language can be found" do
expect(Subtag.find('xxxx')).to be_nil
end
end
describe ".default" do
it "finds from DEFAULT_CODE" do
expect(Subtag.default).to eq Subtag.find('fr')
end
end
describe ".codes" do
it "returns an array of all codes" do
expect(Subtag.codes).to eq %w(en fr de)
end
end
end
|
tigrish/iso
|
spec/lib/iso/language_spec.rb
|
<filename>spec/lib/iso/language_spec.rb
require 'spec_helper'
describe ISO::Language do
let(:language) { ISO::Language.new('de', name: 'German') }
it "is a ISO Subtag" do
expect(language).to be_kind_of(ISO::Subtag)
end
it "has a code" do
expect(language.code).to eq 'de'
end
it "has a name" do
expect(language.name).to eq 'German'
end
describe "#plural_rule_names" do
it "defaults to %w(one other)" do
expect(language.plural_rule_names).to eq ISO::Language::DEFAULT_PLURAL_RULE_NAMES
end
it "is overwriteable" do
language = ISO::Language.new('ja', plural_rule_names: ['other'])
expect(language.plural_rule_names).to eq ['other']
end
end
describe "#direction" do
it "defaults to 'ltr'" do
expect(language.direction).to eq 'ltr'
end
it "is overwriteable" do
language = ISO::Language.new('ar', direction: :rtl)
expect(language.direction).to eq :rtl
end
end
describe ".identify(full_code)" do
it "identifies from 'de'" do
expect(ISO::Language.identify('de')).to eq ISO::Language.new('de')
end
it "identifies from 'fr-CH'" do
expect(ISO::Language.identify('fr-CH')).to eq ISO::Language.new('fr')
end
it "returns nil when it can't identify" do
expect(ISO::Language.identify('csb')).to be_nil
end
end
end
|
tigrish/iso
|
lib/iso.rb
|
require 'i18n'
I18n.load_path << Dir[File.join(File.expand_path(File.dirname(__FILE__) + '/../locales'), '*.yml')]
I18n.load_path.flatten!
require_relative 'iso/tag'
require_relative 'iso/subtag'
require_relative 'iso/language'
require_relative 'iso/region'
require_relative 'iso/un/region'
|
tigrish/iso
|
spec/lib/iso/region_spec.rb
|
require 'spec_helper'
describe ISO::Region do
let(:region) { ISO::Region.new('FR', name: 'France') }
it "is a ISO Subtag" do
expect(region).to be_kind_of(ISO::Subtag)
end
it "has a code" do
expect(region.code).to eq 'FR'
end
it "has a name" do
expect(region.name).to eq 'France'
end
describe ".identify(full_code)" do
it "identifies from 'fr-CH'" do
expect(ISO::Region.identify('fr-CH')).to eq ISO::Region.find('CH')
end
it "identifies from 'es_MX" do
expect(ISO::Region.identify('es_MX')).to eq ISO::Region.find('MX')
end
it "returns nil when it can't identify" do
expect(ISO::Region.identify('gsw')).to be_nil
end
end
end
|
dribbble/assorted
|
assorted.gemspec
|
<reponame>dribbble/assorted<filename>assorted.gemspec<gh_stars>10-100
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'assorted/version'
Gem::Specification.new do |spec|
spec.name = "assorted"
spec.version = Assorted::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.summary = %q{Add sorting scopes `asc` and `desc` to your ActiveRecord models.}
spec.homepage = "https://github.com/dribbble/assorted"
spec.license = "MIT"
spec.files = Dir["lib/**/*"].to_a
spec.test_files = Dir["spec/**/*"].to_a
spec.require_path = "lib"
spec.add_dependency "activerecord", ">= 3"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.1"
spec.add_development_dependency "appraisal", "~> 1.0"
spec.add_development_dependency "sqlite3", "~> 1.3"
end
|
dribbble/assorted
|
spec/lib/assorted/scopes_spec.rb
|
<reponame>dribbble/assorted
require "spec_helper"
RSpec.describe Assorted::Scopes do
it "sorts by created_at by default" do
first = ExampleRecord.create(created_at: 2.days.ago)
second = ExampleRecord.create(created_at: 1.day.ago)
expect(ExampleRecord.asc).to eq([first, second])
expect(ExampleRecord.desc).to eq([second, first])
end
it "sorts by the given column, if provided" do
more = ExampleRecord.create(example_count: 2)
less = ExampleRecord.create(example_count: 1)
expect(ExampleRecord.asc(:example_count)).to eq([less, more])
expect(ExampleRecord.desc(:example_count)).to eq([more, less])
end
it "prevents SQL injection attacks" do
ExampleRecord.create
injection_attempt = "created_at desc; delete * from example_records;"
expect { ExampleRecord.asc(injection_attempt) }.to raise_exception(ActiveRecord::StatementInvalid)
expect(ExampleRecord.count).to eq(1)
end
it "allows an alternate default sorting column to be supplied" do
more = ExampleRecord.create(example_count: 2)
less = ExampleRecord.create(example_count: 1)
class ExampleRecord
assorted default_sort_column: :example_count
end
expect(ExampleRecord.asc).to eq([less, more])
expect(ExampleRecord.desc).to eq([more, less])
end
end
|
dribbble/assorted
|
lib/assorted/scopes.rb
|
module Assorted
module Scopes
def asc(column = sorting_column)
sanitized_order(column, :asc)
end
def desc(column = sorting_column)
sanitized_order(column, :desc)
end
def assorted(options)
assorted_options.merge!(options)
end
private
def sanitized_order(column, direction)
if attribute_names.include?(column.to_s)
order("#{table_name}.#{column} #{direction}")
else
raise ActiveRecord::StatementInvalid, "Unknown column #{column}"
end
end
def sorting_column
assorted_options[:default_sort_column] || Assorted.options[:default_sort_column]
end
def assorted_options
@assorted_options ||= {}
end
end
end
|
dribbble/assorted
|
spec/support/active_record.rb
|
<gh_stars>10-100
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: "spec/test.db")
class ExampleRecord < ActiveRecord::Base
end
RSpec.configure do |config|
config.around do |example|
ActiveRecord::Base.transaction do
ActiveRecord::Migration.verbose = false
ActiveRecord::Migration.create_table(:example_records) do |table|
table.integer :user_id
table.integer :example_count
table.timestamps
end
example.run
ExampleRecord.instance_variable_set(:@assorted_options, nil)
Assorted.instance_variable_set(:@options, nil)
raise ActiveRecord::Rollback
end
end
config.after(:suite) do
ActiveRecord::Base.connection.instance_variable_get("@config").tap do |configuration|
File.delete(configuration[:database])
end
end
end
|
dribbble/assorted
|
lib/assorted.rb
|
require "active_record"
require "assorted/version"
require "assorted/scopes"
module Assorted
def self.options
@options ||= {
default_sort_column: :created_at,
}
end
end
ActiveSupport.on_load(:active_record) do
extend Assorted::Scopes
end
|
dribbble/assorted
|
spec/lib/assorted_spec.rb
|
<filename>spec/lib/assorted_spec.rb
require "spec_helper"
RSpec.describe Assorted do
it "includes itself in ActiveRecord::Base" do
expect(ActiveRecord::Base.ancestors).to include(Assorted::Scopes)
end
describe "#options" do
it "defaults to sort with created_at" do
expect(Assorted.options[:default_sort_column]).to eq :created_at
end
it "remembers the new options given to it" do
Assorted.options[:foo] = :bar
expect(Assorted.options[:foo]).to eq(:bar)
end
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/rubinius.rb
|
module Rubinius
Config = { 'eval.cache' => false }
def synchronize(obj)
yield
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/version.rb
|
module Rubinius
module Bridge
VERSION = "3.0"
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/object.rb
|
class Object
def StringValue(obj)
return obj if obj.kind_of?(String)
begin
obj.to_str
rescue Exception => orig
raise TypeError,
"Coercion error: #{obj.inspect}.to_str => String failed",
orig
end
return ret if ret.kind_of?(String)
msg = "Coercion error: obj.to_st did NOT return a String (was #{ret.class})"
raise TypeError, msg
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/tuple.rb
|
module Rubinius
class Tuple < Array
def copy_from(other, start, length, dest)
length.times do |i|
self[dest + i] = other[start + i]
end
end
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/array.rb
|
<reponame>rubinius/rubinius-bridge
class Array
def to_tuple
Rubinius::Tuple.new self
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/executable.rb
|
<filename>lib/rubinius/bridge/executable.rb
module Rubinius
class Executable
attr_accessor :primitive
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge.rb
|
require "redcard"
require "rubinius/bridge/version"
unless RedCard.check :rubinius
require "rubinius/bridge/object"
require "rubinius/bridge/array"
require "rubinius/bridge/string"
require "rubinius/bridge/rubinius"
require "rubinius/bridge/compiled_code"
require "rubinius/bridge/encoding"
require "rubinius/bridge/exception"
require "rubinius/bridge/executable"
require "rubinius/bridge/iseq"
require "rubinius/bridge/lookup_table"
require "rubinius/bridge/tuple"
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/encoding.rb
|
unless RedCard.check "1.9"
class Encoding
attr_reader :name
def initialize(name="US-ASCII")
@name = name
end
ASCII_8BIT = new "ASCII-8BIT"
end
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/lookup_table.rb
|
<reponame>rubinius/rubinius-bridge
module Rubinius
LookupTable = Hash
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/string.rb
|
<reponame>rubinius/rubinius-bridge
class String
alias_method :append, :<<
alias_method :bytesize, :size unless method_defined?(:bytesize)
def data
self
end
unless RedCard.check "1.9"
def encoding
@encoding ||= Encoding.new
end
def force_encoding(encoding)
@encoding = encoding
self
end
end
end
|
rubinius/rubinius-bridge
|
rubinius-bridge.gemspec
|
<reponame>rubinius/rubinius-bridge<gh_stars>1-10
# coding: utf-8
require './lib/rubinius/bridge/version'
Gem::Specification.new do |spec|
spec.name = "rubinius-bridge"
spec.version = Rubinius::Bridge::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.description = <<-EOD
Classes and methods to run other Rubinius tools under MRI.
Rubinius needs to bootstrap building its core library and code tools
because they are written in Ruby. One way to do this is to run the
code tools under MRI. To do so requires adding some classes and methods
that are built into Rubinius.
EOD
spec.summary = %q{Classes and methods to run other Rubinius tools under MRI.}
spec.homepage = "https://github.com/rubinius/rubinius-bridge"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "redcard", "~> 1.0"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake", ">= 12.3.3"
end
|
rubinius/rubinius-bridge
|
lib/rubinius/bridge/exception.rb
|
<reponame>rubinius/rubinius-bridge
class SyntaxError
def self.from(message, column, line, code, file)
message << " #{file}:#{line}:#{column}\n #{code}"
SyntaxError.new message
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.