repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
drefuss/rubequ
|
app/controllers/songs_controller.rb
|
class SongsController < ApplicationController
before_action :set_song, only: [:show, :lyrics, :queue_add, :edit, :update, :destroy]
# GET /songs
# GET /songs.json
def index
@songs = Song.all
end
# GET /songs/1
# GET /songs/1.json
def show
end
def lyrics
respond_to do |format|
format.json {render json: @song.lyrics.to_json }
end
end
def current_song
@song = Song.current_song
respond_to do |format|
format.json { render :json => @song }
end
end
def songs_in_queue
@songs = Song.all_in_queue
respond_to do |format|
format.json { render :json => @songs }
end
end
def queue_add
respond_to do |format|
if @song.add_to_queue
format.json { render json: @song, status: :created }
else
format.json { render json: @song.errors, status: :unprocessable_entity }
end
end
end
def play
Song.play
@song = Song.current_song
respond_to do |format|
format.json { render :json => @song }
end
end
def pause
Song.pause
@song = Song.current_song
respond_to do |format|
format.json { render :json => @song }
end
end
def next
Song.next
@song = Song.current_song
respond_to do |format|
format.json { render :json => @song }
end
end
# GET /songs/new
def new
@song = Song.new
end
# GET /songs/1/edit
def edit
end
# POST /songs
# POST /songs.json
def create
@song = Song.new(song_params)
respond_to do |format|
if @song.save
format.html { redirect_to @song, notice: 'Song was successfully created.' }
format.json { render action: 'show', status: :created, location: @song }
else
format.html { render action: 'new' }
format.json { render json: @song.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /songs/1
# PATCH/PUT /songs/1.json
def update
respond_to do |format|
if @song.update(song_params)
format.html { redirect_to @song, notice: 'Song was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @song.errors, status: :unprocessable_entity }
end
end
end
# DELETE /songs/1
# DELETE /songs/1.json
def destroy
@song.destroy
respond_to do |format|
format.html { redirect_to songs_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_song
song_id = params[:id].blank? ? params[:song_id] : params[:id]
@song = Song.find(song_id)
end
# Never trust parameters from the scary internet, only allow the white list through.
def song_params
params.require(:song).permit(:name, :band, :album, :album_cover, :release_date, :mp3)
end
end
|
drefuss/rubequ
|
app/controllers/root_controller.rb
|
<reponame>drefuss/rubequ<gh_stars>0
class RootController < ApplicationController
def index
end
def connected
mpd = RubequMpd::Mpd.new
connected = mpd.connected?
mpd.disconnect
respond_to do |format|
format.json { render :json => connected }
end
end
def volume
mpd = RubequMpd::Mpd.new
volume = mpd.volume
mpd.disconnect
respond_to do |format|
format.json { render :json => volume }
end
end
def update_volume
mpd = RubequMpd::Mpd.new
volume = mpd.volume(params[:volume])
mpd.disconnect
respond_to do |format|
format.json { render :json => volume }
end
end
end
|
drefuss/rubequ
|
config/initializers/song_information_init.rb
|
require 'rubequ_song_information'
include RubequSongInformation
|
drefuss/rubequ
|
spec/spec_helper.rb
|
<reponame>drefuss/rubequ
require 'spork'
require 'ostruct'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
### Part of a Spork hack.
# Emulate initializer set_clear_dependencies_hook in
# railties/lib/rails/application/bootstrap.rb
ActiveSupport::Dependencies.clear
end
end
Spork.each_run do
$rspec_start_time = Time.now
Dir[Rails.root.join("app/**/*.rb")].each{|f| load f}
end
|
drefuss/rubequ
|
config/initializers/rubequ_mpd_init.rb
|
<reponame>drefuss/rubequ<filename>config/initializers/rubequ_mpd_init.rb
require 'rubequ_mpd'
include RubequMpd
RubequMpd.mpd_server = "127.0.0.1"
RubequMpd.mpd_port = 6600
|
drefuss/rubequ
|
lib/rubequ_song_information.rb
|
require 'discogs'
require 'lyricfy'
module RubequSongInformation
class AlbumCover
def initialize
end
def get_cover(name)
begin
wrapper = Discogs::Wrapper.new("rasplay")
if wrapper.nil?
default_image
else
search = wrapper.search(name)
results = search.results.first
results.thumb
end
rescue Exception => e
puts e
default_image
end
end
def default_image
"http://s.pixogs.com/images/record150.png"
end
end
class Lyrics
def initialize
end
def get_lyrics(band, song_name)
fetcher = Lyricfy::Fetcher.new
song = fetcher.search band, song_name
song.body("<br>")
end
end
end
|
drefuss/rubequ
|
db/migrate/20130711024929_add_attachment_mp3_to_songs.rb
|
<filename>db/migrate/20130711024929_add_attachment_mp3_to_songs.rb
class AddAttachmentMp3ToSongs < ActiveRecord::Migration
def self.up
change_table :songs do |t|
t.attachment :mp3
end
end
def self.down
drop_attached_file :songs, :mp3
end
end
|
drefuss/rubequ
|
app/views/songs/index.json.jbuilder
|
json.array!(@songs) do |song|
json.extract! song, :name, :band, :album, :album_cover, :release_date
json.url song_url(song, format: :json)
end
|
drefuss/rubequ
|
app/views/songs/show.json.jbuilder
|
<gh_stars>0
json.extract! @song, :name, :band, :album, :album_cover, :release_date, :created_at, :updated_at
|
drefuss/rubequ
|
spec/models/song_spec.rb
|
require 'spec_helper'
describe Song do
before(:each) do
@song = FactoryGirl.build(:song)
end
it "should validate that name can not be blank" do
@song.name = ""
@song.should have(1).error_on(:name)
end
it "should validate that band can not be blank" do
@song.band = ""
@song.should have(1).error_on(:band)
end
it "should validate that mp3 can not be blank" do
@song.mp3 = nil
@song.should have(1).error_on(:mp3)
end
it "should replace the public folder from the path to get the download url for the mp3" do
@song.mp3.stub(:path).and_return("public/test/music/imsexyandiknowit.mp3")
@song.mp3_public_path.should eq "/test/music/imsexyandiknowit.mp3"
end
it "release date formatted should return the date as mm/dd/yyyy" do
@song.release_date_formatted.should eq "06/21/2011"
end
it "combines the band and the song name together" do
@song.band_and_song_name_formatted.should eq "LMAFO I'm Sexy And I Know It"
end
end
|
drefuss/rubequ
|
app/models/song.rb
|
class Song < ActiveRecord::Base
if(Rails.env.test? || Rails.env.development?)
has_attached_file :mp3, :path => "public/music/:file_path/:custom_filename"
end
validates_presence_of :name,
:band,
:mp3
before_create :set_album_cover
default_scope { order('created_at DESC') }
def as_json(options={})
{
:id => self.id,
:album => self.album,
:album_cover => self.album_cover,
:band => self.band,
:name => self.name,
:release_date => self.release_date_formatted,
:mp3_path => self.mp3_public_path,
:in_queue => self.in_queue?
}
end
def mp3_public_path
self.mp3.blank? ? "" : self.mp3.path.gsub!("public", "")
end
def release_date_formatted
self.release_date.blank? ? "" : self.release_date.strftime("%m/%d/%Y")
end
def band_and_song_name_formatted
self.band + " " + self.name
end
def set_album_cover
song_info = RubequSongInformation::AlbumCover.new
self.album_cover = song_info.get_cover(self.band_and_song_name_formatted)
end
def lyrics
{
:lyrics => RubequSongInformation::Lyrics.new.get_lyrics(self.band, self.name)
}
end
def in_queue?
mpd = RubequMpd::Mpd.new
mpd.update_song_list
song = mpd.song_by_file(self.mp3.path.gsub("public/music/", ""))
result = song.nil? ? false : mpd.song_is_in_queue?(song)
mpd.disconnect
result
end
def self.all_in_queue
mpd = RubequMpd::Mpd.new
return nil unless mpd.connected?
queued_songs = mpd.queue
current_song = mpd.current_song
mpd.disconnect
songs = []
song_db = Song.all
current_song_file = current_song.blank? ? nil : current_song.file
queued_songs.each do |qs|
song = song_db.find { |s| s.mp3.path.include?(qs.file) }
if !song.blank? && song.mp3.path.gsub("public/music/", "") != current_song_file
songs << song
end
end
songs
end
def self.current_song
mpd = RubequMpd::Mpd.new
song = mpd.current_song
mpd.disconnect
song.blank? ? nil : Song.all.find { |s| s.mp3.path.include?(song.file) }
end
def add_to_queue
mpd = RubequMpd::Mpd.new
song = mpd.song_by_file(self.mp3.path.gsub("public/music/", ""))
result = mpd.queue_add(song)
mpd.play if mpd.current_song.nil?
mpd.disconnect
result
end
def self.play
mpd = RubequMpd::Mpd.new
mpd.play
mpd.disconnect
end
def self.pause
mpd = RubequMpd::Mpd.new
mpd.pause
mpd.disconnect
end
def self.next
mpd = RubequMpd::Mpd.new
mpd.next
mpd.disconnect
end
end
|
drefuss/rubequ
|
spec/factories/songs.rb
|
<filename>spec/factories/songs.rb
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :song do
name "I'm Sexy And I Know It"
band "LMAFO"
album "Sorry For Party Rocking"
album_cover "http://a5.mzstatic.com/us/r1000/086/Features/1f/76/c9/dj.uqxkqdqp.170x170-75.jpg"
release_date "2011-06-21 00:00:00"
mp3 File.new(Rails.root + 'spec/factories/music/ImSexyAndIKnowIt.mp3')
end
end
|
drefuss/rubequ
|
spec/controllers/songs_controller_spec.rb
|
require 'spec_helper'
describe SongsController do
before(:each) do
@song = stub_model(Song, :id => 1)
Song.stub(:find).and_return(@song)
Song.stub(:all).and_return([@song])
Song.stub(:destroy).and_return(true)
Song.any_instance.stub(:in_queue).and_return(false)
Song.any_instance.stub(:save_attached_files).and_return(true)
Song.any_instance.stub(:set_album_cover).and_return("http://a5.mzstatic.com/us/r1000/086/Features/1f/76/c9/dj.uqxkqdqp.170x170-75.jpg")
Song.any_instance.stub(:lyrics).and_return("This is the awesome stuff.")
end
def valid_attributes
{ :name => "<NAME>", :band => "LMFAO", :mp3 => Rack::Test::UploadedFile.new(Rails.root + 'spec/factories/music/ImSexyAndIKnowIt.mp3') }
end
describe "GET 'index'" do
it "returns http success" do
get 'index', :format => :json
response.should be_success
end
end
describe "GET 'new'" do
it "returns http success" do
get 'new'
assigns(:song).should be_a_new(Song)
response.should be_success
end
end
describe "GET 'show'" do
it "returns http success" do
get 'show', :id => @song.id, :format => :json
response.should be_success
end
end
describe "GET 'edit'" do
it "returns http success" do
get 'edit', :id => @song.id
response.should be_success
end
end
describe "GET 'lyrics'" do
it "returns http success" do
get 'lyrics', :song_id => @song.id, :format => :json
response.body.should eq "\"This is the awesome stuff.\""
response.should be_success
end
end
describe "POST 'create'" do
it "assigns a newly created song as @song" do
post :create, {:song => valid_attributes, :format => :json }
assigns(:song).should be_a(Song)
assigns(:song).should be_persisted
end
it "renders a 201 status created code" do
post :create, {:song => valid_attributes, :format => :json }
response.status.should eq 201
end
describe "with invalid params" do
it "assigns a newly created but unsaved song as @song" do
Song.any_instance.stub(:save).and_return(false)
post :create, {:song => { "name" => "" }, :format => :json }
assigns(:song).should be_a_new(Song)
end
end
end
describe "PUT 'update'" do
it "returns updated song in json format" do
put 'update', { :id => @song.id, :song => valid_attributes, :format => :json }
response.should be_success
end
end
describe "DESTROY 'destroy'" do
it "should remove the song" do
@song.should_receive(:destroy)
ass_params = { :id => @song.id, :format => :json }
delete 'destroy', ass_params
response.should be_success
end
end
end
|
drefuss/rubequ
|
config/initializers/secret_token.rb
|
# Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
#https://github.com/gedankenstuecke/snpr/blob/master/config/initializers/secret_token.rb
#execute in the project root.
#rake secret > secret_token
begin
token_file = Rails.root.to_s + "/secret_token"
to_load = open(token_file).read
Rubequ::Application.configure do
config.secret_token = to_load
end
rescue LoadError, Errno::ENOENT => e
raise "Secret token couldn't be loaded! Error: #{e}"
end
|
pandamouse/rqrcode-rails3
|
test/unit/size_calculator_test.rb
|
require 'test_helper'
class RQRCode::SizeCalculatorTest < ActiveSupport::TestCase
include RQRCode::SizeCalculator
test "size returned is 1 for 'apple'" do
assert_equal(1, minimum_qr_size_from_string('apple'))
end
test "size returned is 5 for 'http://guides.rubyonrails.org/testing.html'" do
assert_equal(5, minimum_qr_size_from_string('http://guides.rubyonrails.org/testing.html'))
end
test "size returned is 18 for long long string" do
assert_equal(18, minimum_qr_size_from_string('a'*300))
end
end
|
pandamouse/rqrcode-rails3
|
test/dummy/app/controllers/home_controller.rb
|
<gh_stars>10-100
class HomeController < ApplicationController
def index
respond_to do |format|
format.html
format.svg { render options }
format.png { render options }
format.jpeg { render options }
format.gif { render options }
end
end
private
def options
{:qrcode => "http://helloworld.com", :size => 4}
end
end
|
pandamouse/rqrcode-rails3
|
test/dummy/config/routes.rb
|
<gh_stars>10-100
Dummy::Application.routes.draw do
get "/home(.:format)", :to => "home#index", :as => :home
get "/", :to => "home#index"
end
|
pandamouse/rqrcode-rails3
|
test/integration/navigation_test.rb
|
<reponame>pandamouse/rqrcode-rails3
require 'test_helper'
class NavigationTest < ActiveSupport::IntegrationCase
test "truth" do
assert_kind_of Dummy::Application, Rails.application
end
test 'svg request returns an SVG file' do
visit home_path
click_link 'SVG'
assert_equal 'image/svg+xml; charset=utf-8', headers['Content-Type']
assert_equal File.read('test/support/data/qrcode.svg'), page.source
end
test 'png request returns a PNG file' do
image_test('png')
end
test 'jpeg request returns a JPEG file' do
image_test('jpeg')
end
test 'gif request returns a GIF file' do
image_test('gif')
end
protected
def headers
page.response_headers
end
def image_test(format)
visit home_path
click_link format.upcase
assert_equal "image/#{format}; charset=utf-8", headers['Content-Type']
assert_equal File.read("test/support/data/qrcode.#{format}")[0,4], page.source.force_encoding("UTF-8")[0,4]
end
end
|
pandamouse/rqrcode-rails3
|
test/rqrcode_svg_test.rb
|
<filename>test/rqrcode_svg_test.rb<gh_stars>10-100
require 'test_helper'
class RQRCode::SVGTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, RQRCode
end
end
|
pandamouse/rqrcode-rails3
|
rqrcode_rails3.gemspec
|
<filename>rqrcode_rails3.gemspec
# Provide a simple gemspec so you can easily use your enginex
# project in your rails apps through git.
Gem::Specification.new do |s|
s.name = "rqrcode-rails3"
s.summary = "Render QR codes with Rails 3"
s.description = "Render QR codes with Rails 3"
s.files = Dir["{app,lib,config}/**/*"] + ["MIT-LICENSE", "Rakefile", "Gemfile", "README.md"]
s.author = "<NAME>"
s.email = "<EMAIL>"
s.homepage = "http://github.com/samvincent/rqrcode-rails3"
s.version = "0.1.7"
s.add_dependency 'rqrcode', '>= 0.4.2'
end
|
balasankarc/ruby-redis-store
|
lib/redis/store/version.rb
|
<filename>lib/redis/store/version.rb
class Redis
class Store < self
VERSION = '1.1.6'
end
end
|
balasankarc/ruby-redis-store
|
debian/ruby-tests.rake
|
require 'gem2deb/rake/testtask'
task :default do
Rake::Task[:start_redis].invoke
failed = false
begin
Rake::Task[:test].invoke
rescue
failed = true
end
Rake::Task[:stop_redis].invoke
if failed
fail 'Tests failed'
end
end
task :start_redis do
sh 'redis-server --daemonize yes --port 6379&'
sh 'redis-server --daemonize yes --port 6380&'
sh 'redis-server --daemonize yes --port 6381&'
end
Rake::TestTask.new do |t|
t.libs << 'test'
t.test_files = FileList['test/*/*_test.rb']
end
task :stop_redis do
sh 'pkill redis-server'
end
|
kete/oembed_provider
|
lib/oembed_provider.rb
|
require 'addressable/uri'
require 'oembed_providable'
# set OembedProvider.provide_name, etc. in your config/initializers or somewhere
class OembedProvider
class << self
def provider_url
@@provider_url ||= String.new
end
def provider_url=(url)
@@provider_url = url
end
def provider_name
@@provider_name ||= String.new
end
def provider_name=(name)
@@provider_name = name
end
def cache_age
@@cache_age ||= nil
end
def cache_age=(age)
@@cache_age = age
end
def version
"1.0"
end
# every request has these, mostly required
# mostly site wide
# version is special case
def base_attributes
[:provider_url,
:provider_name,
:cache_age,
:version]
end
# optional attributes
# that are specific to an instance of the providable model
def optional_attributes
[:title,
:author_name,
:author_url,
:thumbnail_url,
:thumbnail_width,
:thumbnail_height]
end
# these may be required depending on type
# see 2.3.4.1 - 2.3.4.4 of spec
# type specific attributes
# all attributes listed for these types are required
# the empty link array shows that nothing is required
def required_attributes
{ :photo => [:url, :width, :height],
:video => [:html, :width, :height],
:link => [],
:rich => [:html, :width, :height] }
end
def controller_model_maps
@@controller_model_maps ||= Hash.new
end
def controller_model_maps=(hash_map)
@@controller_model_maps = hash_map
end
def find_provided_from(url)
url = Addressable::URI.parse(url)
submitted_url_params = ActionController::Routing::Routes.recognize_path(url.path, :method=>:get)
controller = submitted_url_params[:controller]
id = submitted_url_params[:id]
# handle special cases where controllers are directly configured to point at a specific model
model = OembedProvider.controller_model_maps[controller]
# otherwise we use convention over configuration to determine model
model = controller.singularize.camelize unless model
model.constantize.find(id)
end
end
end
|
kete/oembed_provider
|
config/routes.rb
|
<reponame>kete/oembed_provider
# extend routes for oembed provider endpoint
ActionController::Routing::Routes.draw do |map|
# only one route needed
map.with_options :controller => 'oembed_provider' do |oembed_provider|
oembed_provider.connect 'oembed.:format', :action => 'endpoint'
oembed_provider.connect 'oembed', :action => 'endpoint'
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/test/functional/oembed_provider_controller_test.rb
|
<gh_stars>1-10
# -*- coding: utf-8 -*-
require 'test_helper'
class OembedProviderControllerTest < ActionController::TestCase
context "The oembed provider controller" do
setup do
@photo = Factory.create(:photo)
end
should "endpoint" do
get :endpoint, :url => "http://example.com/photos/#{@photo.id}"
assert_response :success
end
should "endpoint with format json" do
@request.accept = "text/javascript"
get :endpoint, :url => "http://example.com/photos/#{@photo.id}", :format => 'json'
assert_response :success
end
should "endpoint with format json and callback, return json-p" do
@request.accept = "text/javascript"
get :endpoint, :url => "http://example.com/photos/#{@photo.id}", :format => 'json', :callback => 'myCallback'
assert_response :success
end
should "endpoint with format xml" do
@request.accept = "text/xml"
get :endpoint, :url => "http://example.com/photos/#{@photo.id}", :format => 'xml'
assert_response :success
end
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/app/models/item.rb
|
<reponame>kete/oembed_provider<filename>test/full_2_3_5_app_with_tests/app/models/item.rb
class Item < ActiveRecord::Base
include OembedProvidable
oembed_providable_as :link, :title => :label
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/test/selenium.rb
|
# -*- coding: utf-8 -*-
require 'test_helper'
# This file is not in integration/ because when run with
# 'rake', it causes segfaults in the test suite
# ATTN: Before runnings these tests, be sure to turn
# off all extensions and popup blockers in Safari
class ActiveSupport::TestCase
self.use_transactional_fixtures = true
setup do |session|
session.host! "localhost:3001"
end
end
Webrat.configure do |config|
config.mode = :selenium
config.application_environment = :test
config.selenium_browser_key = '*safari'
end
class SeleniumTest < ActionController::IntegrationTest
context "Using Selenium to test javascript functionality" do
# DEBUG: This works so if the others don't, try just this one
# should "be able to visit the homepage" do
# visit "/"
# assert_contain "Welcome aboard"
# end
should "be able to translate an item via AJAX" do
item = create_item
click_link "Français"
assert current_url =~ /\/en\/items\/#{item.id}$/
assert_contain "Translate from English to Français"
fill_in 'item_translation_label', :with => 'Certains Point'
click_button 'Create'
assert_contain 'Translation was successfully created.'
end
should "be able to switch translations" do
item = create_item
click_link "Français"
assert current_url =~ /\/en\/items\/#{item.id}$/
assert_contain "Translate from English to Français"
click_link "Suomi"
assert current_url =~ /\/en\/items\/#{item.id}$/
assert_contain "Translate from English to Suomi"
end
should "be able to close the translations box" do
item = create_item
click_link "Français"
click_link "[close]"
assert_not_contain "Translate from English to Français"
end
should "be able to use the auto translate functionality" do
item = create_item
visit "/en/items/#{item.id}/translations/new?to_locale=fr"
click_link '[auto translate]'
sleep 1 # ugly way to wait for google to do it's thing
click_button 'Create'
assert_contain 'Translation was successfully created.'
assert_contain 'Certains Point'
end
end
private
def create_item
visit "/en/items"
click_link "New item"
fill_in 'item_label', :with => 'Some Item'
fill_in 'item_value', :with => '$3.50'
fill_in 'item_locale', :with => 'en'
click_button 'Create'
assert_contain 'Item was successfully created.'
Item.last
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/config/initializers/oembed_provider.rb
|
OembedProvider.provider_url = "http://example.com"
OembedProvider.provider_name = "Example.com"
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/test/integration/oembed_test.rb
|
<gh_stars>1-10
# -*- coding: utf-8 -*-
require 'test_helper'
Webrat.configure do |config|
config.mode = :rails
end
class OembedTest < ActionController::IntegrationTest
context "A providable object when its url is request from the oembed endpoint" do
setup do
@photo = Factory.create(:photo)
@url_without_protocol = "example.com/photos/#{@photo.id}"
@escaped_url = "http%3A//#{@url_without_protocol}"
@normal_url = "http://#{@url_without_protocol}"
end
should "return correct json for the providable object" do
visit "/oembed?url=#{@escaped_url}"
assert_json_equal_to(response.body)
end
should "return correct json for the providable object when .json" do
visit "/oembed.json?url=#{@escaped_url}"
assert_json_equal_to(response.body)
end
should "return correct json for the providable object when query string specifies format=json" do
visit "/oembed?url=#{@escaped_url}&format=json"
assert_json_equal_to(response.body)
end
should "return correct json-p for the providable object when .json and callback specified" do
callback_name = 'myCallback'
visit "/oembed.json?url=#{@escaped_url}&callback=#{callback_name}"
assert response.body.include?(callback_name)
assert_json_equal_to(response.body.sub("#{callback_name}(", '').chomp(');'))
end
should "return correct json-p for the providable object when .json and variable specified" do
variable_name = 'myVar'
visit "/oembed.json?url=#{@escaped_url}&variable=#{variable_name}"
assert response.body.include?(variable_name)
assert_json_equal_to(response.body.sub("var #{variable_name} = ", '').chomp(';'))
end
should "return correct json-p for the providable object when .json and variable and callback specified" do
variable_name = 'myVar'
callback_name = 'myCallback'
visit "/oembed.json?url=#{@escaped_url}&variable=#{variable_name}&callback=#{callback_name}"
assert response.body.include?(variable_name)
assert response.body.include?(callback_name)
stripped_to_json = response.body.sub("var #{variable_name} = ", '').sub("\n#{callback_name}(#{variable_name})", '').chomp(';').chomp(';')
assert_json_equal_to(stripped_to_json)
end
should "return correct xml for the providable object when .xml" do
visit "/oembed.xml?url=#{@escaped_url}"
assert_equal @photo.oembed_response.to_xml, response.body
end
should "return correct xml for the providable object when query string specifies format=xml" do
visit "/oembed?url=#{@escaped_url}&format=xml"
assert_equal @photo.oembed_response.to_xml, response.body
end
# test helper here as integration test rather than unit/helpers
# only one helper and easier to do and effective in practice
context "when visiting providable url, the page" do
should "oembed links in the header" do
visit @normal_url
assert response.body.include?("application/json+oembed")
assert response.body.include?("/oembed?url=#{@escaped_url}")
assert response.body.include?("application/xml+oembed")
assert response.body.include?("/oembed.xml?url=#{@escaped_url}")
end
end
# WARNING: maxheight and maxwidth parameter passing
# results in correct version of image, etc.
# is left to application specific testing by application using the engine
# in other words, implement it in YOUR tests
end
private
def assert_json_equal_to(response_body)
assert_equal ActiveSupport::JSON.decode(@photo.oembed_response.to_json), ActiveSupport::JSON.decode(response_body)
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/config/environment.rb
|
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
# thanks to http://www.justinball.com/2009/06/16/testing-rails-engine-gems/
class TestGemLocator < Rails::Plugin::Locator
def plugins
Rails::Plugin.new(File.join(File.dirname(__FILE__), *%w(.. .. ..)))
end
end
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# this allows us to place locale in URL
# without messing with the rest of the rails routing mechanism
# config.gem "routing_filter" # using plugin for the moment
# config.gem "oembed_provider"
config.plugin_locators << TestGemLocator
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
|
kete/oembed_provider
|
lib/oembed_providable.rb
|
require 'oembed_provider'
require 'builder'
module OembedProvidable #:nodoc:
def self.included(base)
base.send(:include, OembedProvidable::Provided)
end
# use this to make your model able to respond to requests
# against the OembedProviderController
module Provided
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def oembed_providable_as(*args)
# don't allow multiple calls
return if self.included_modules.include?(OembedProvidable::Provided::InstanceMethods)
send :include, OembedProvidable::Provided::InstanceMethods
specs = args.last.is_a?(Hash) ? args.pop : Hash.new
oembed_type = args.first
if !oembed_type.is_a?(Symbol) || ![:photo, :video, :link, :rich].include?(oembed_type)
raise ArgumentError, "oEmbed type must be :photo, :video, :link, or :rich"
end
# create the scoped oembed_response model
const_set("OembedResponse", Class.new).class_eval do
cattr_accessor :providable_class
self.providable_class = self.name.split('::').first.constantize
cattr_accessor :providable_specs
self.providable_specs = specs
cattr_accessor :oembed_version
self.oembed_version = OembedProvider.version
cattr_accessor :providable_oembed_type
self.providable_oembed_type = oembed_type
the_provider_name = specs[:provider_name].present? ? specs[:provider_name] : OembedProvider.provider_name
raise ArgumentError, "Missing provider_name setting in either OembedProvider.provider_name or oembed_providable_as spec." unless the_provider_name.present?
cattr_accessor :providable_provider_name
self.providable_provider_name = the_provider_name
the_provider_url = specs[:provider_url].present? ? specs[:provider_url] : OembedProvider.provider_url
raise ArgumentError, "Missing provider_url setting in either OembedProvider.provider_url or oembed_providable_as spec." unless the_provider_url.present?
cattr_accessor :providable_provider_url
self.providable_provider_url = the_provider_url
# cache_age is optional and can be nil
the_cache_age = specs[:cache_age].present? ? specs[:cache_age] : OembedProvider.cache_age
cattr_accessor :providable_cache_age
self.providable_cache_age = the_cache_age
# these are what the response should return
# as per the oEmbed Spec
# http://oembed.com/#section2 - 2.3.4
# :type is required, but is model wide and set via oembed_providable_as
# :version is required and is handled below
attributes_to_define = OembedProvider.optional_attributes
attributes_to_define += OembedProvider.required_attributes[oembed_type]
# site wide values
# :provider_name, :provider_url, :cache_age
# can be set via oembed_providable_as
# or set via OembedProvider initialization
attributes_to_define += OembedProvider.base_attributes
# not relevant to links, but everything else
attributes_to_define += [:maxheight, :maxwidth] unless oembed_type == :link
cattr_accessor :providable_all_attributes
self.providable_all_attributes = attributes_to_define
attributes_to_define.each do |attr|
attr_accessor attr
end
# datastructure is hash
# with attribute name as key
# and method to call on providable as value
# both as symbol
# oembed_providable_as can specify method to call for an attribute
def self.method_specs_for(attributes)
method_specs = Hash.new
attributes.each do |attr|
if providable_specs.keys.include?(attr)
method_specs[attr] = providable_specs[attr]
else
method_specs[attr] = attr
end
end
method_specs
end
cattr_accessor :optional_attributes_specs
self.optional_attributes_specs = method_specs_for(OembedProvider.optional_attributes)
cattr_accessor :required_attributes_specs
self.required_attributes_specs = method_specs_for(OembedProvider.required_attributes[oembed_type])
# options are added to handle passing maxwidth and maxheight
# relevant to oembed types photo, video, and rich
# if they have a thumbnail, then these also much not be bigger
# than maxwidth, maxheight
def initialize(providable, options = {})
self.version = self.class.oembed_version
# we set maxwidth, maxheight first
# so subsequent calls to providable.send(some_method_name)
# can use them to adjust their values
unless type == :link
self.maxheight = options[:maxheight].to_i if options[:maxheight].present?
self.maxwidth = options[:maxwidth].to_i if options[:maxwidth].present?
providable.oembed_max_dimensions = { :height => maxheight, :width => maxwidth }
end
self.class.required_attributes_specs.each do |k,v|
value = providable.send(v)
raise ArgumentError, "#{k} is required for an oEmbed response." if value.blank?
send(k.to_s + '=', value)
end
self.class.optional_attributes_specs.each do |k,v|
send(k.to_s + '=', providable.send(v))
end
self.provider_name = self.class.providable_provider_name
self.provider_url = self.class.providable_provider_url
self.cache_age = self.class.providable_cache_age
end
def type
self.class.providable_oembed_type
end
# because this isn't an AR record, doesn't include to_xml
# plus we need a custom
# root node needs to replaced with oembed rather than oembed_response
def to_xml
attributes = self.class.providable_all_attributes
builder = Nokogiri::XML::Builder.new do |xml|
xml.oembed {
attributes.each do |attr|
next if attr.to_s.include?('max')
value = self.send(attr)
xml.send(attr, value) if value.present?
end
}
end
builder.to_xml
end
# override default to_json
def as_json(options = {})
as_json = super(options)
attributes = self.class.providable_all_attributes
as_json.delete_if { |k,v| v.blank? }
as_json.delete_if { |k,v| k.include?('max') }
as_json
end
end
end
def oembed_type
self::OembedResponse.providable_oembed_type
end
end
module InstanceMethods
def oembed_response(options = {})
@oembed_response ||= self.class::OembedResponse.new(self, options)
end
def oembed_max_dimensions=(options)
options = { :height => nil, :width => nil } if options.blank?
@oembed_max_dimensions = options
end
def oembed_max_dimensions
@oembed_max_dimensions || { :height => nil, :width => nil }
end
end
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/test/unit/oembed_providable_test.rb
|
# -*- coding: utf-8 -*-
require 'test_helper'
class OembedProvidableTest < ActiveSupport::TestCase
n = 0
context "A model class that includes OembedProvidable" do
context "when declaring oembed_providable_as" do
setup do
n += 1
@a_class_name = "Klass#{n}"
Object.const_set(@a_class_name, Class.new(ActiveRecord::Base)).class_eval do
include OembedProvidable
end
@a_class = @a_class_name.constantize
end
should "not be able to be able to declare oembed_providable_as without an argument for type" do
assert_raise(ArgumentError) { @a_class.send(:oembed_providable_as) }
end
should "be able to be able to declare oembed_providable_as with a type" do
assert_nothing_raised { @a_class.send(:oembed_providable_as, :link) }
end
should "be able to be able to declare oembed_providable_as with a type and a hash for a spec" do
assert_nothing_raised { @a_class.send(:oembed_providable_as, :link, { :title => :label }) }
end
should "have the ability to return an oembed_type" do
@a_class.send(:oembed_providable_as, :link)
assert @a_class.respond_to?(:oembed_type)
assert_equal @a_class.oembed_type, :link
end
end
context "will have method" do
setup do
@method_specs = Hash.new
end
context "methods_specs_for that" do
should "return an array of hashes that match defaults when there is no hash of overriding specs" do
assert_nothing_raised { Photo::OembedResponse.send(:method_specs_for, OembedProvider.optional_attributes) }
OembedProvider.optional_attributes.each { |attr| @method_specs[attr] = attr }
results_for_test = Photo::OembedResponse.send(:method_specs_for, OembedProvider.optional_attributes)
assert_equal results_for_test, @method_specs
end
should "return an array of hashes that take into account overriding specs" do
OembedProvider.optional_attributes.each { |attr| @method_specs[attr] = attr }
@method_specs[:title] = :label
results_for_test = Item::OembedResponse.send(:method_specs_for, OembedProvider.optional_attributes)
assert_equal results_for_test, @method_specs
end
end
context "optional_attributes_specs set and " do
should "match the OembedProvider defaults when there is no hash of overriding specs in the oembed_providable_as call" do
assert Photo::OembedResponse.respond_to?(:optional_attributes_specs)
OembedProvider.optional_attributes.each { |attr| @method_specs[attr] = attr }
assert_equal Photo::OembedResponse.optional_attributes_specs, @method_specs
end
should "match the oembed_providable_as specs if they are specified" do
OembedProvider.optional_attributes.each { |attr| @method_specs[attr] = attr }
@method_specs[:title] = :label
assert_equal Item::OembedResponse.optional_attributes_specs, @method_specs
end
end
context "required_attributes_specs set and " do
should "match the OembedProvider defaults when there is no hash of overriding specs in the oembed_providable_as call" do
assert Photo::OembedResponse.respond_to?(:required_attributes_specs)
OembedProvider.required_attributes[:photo].each { |attr| @method_specs[attr] = attr }
assert_equal Photo::OembedResponse.required_attributes_specs, @method_specs
end
should "match the oembed_providable_as specs if they are specified" do
Object.const_set("RichItem", Class.new(ActiveRecord::Base)).class_eval do
include OembedProvidable
oembed_providable_as :rich, :html => :description
def description
"<h1>some html</h1>"
end
end
OembedProvider.required_attributes[:rich].each { |attr| @method_specs[attr] = attr }
@method_specs[:html] = :description
assert_equal RichItem::OembedResponse.required_attributes_specs, @method_specs
end
end
context "providable_all_attributes set and " do
should "have all relevant attributes for the type" do
assert Item::OembedResponse.respond_to?(:providable_all_attributes)
all_attributes = OembedProvider.optional_attributes +
OembedProvider.required_attributes[:link] +
OembedProvider.base_attributes
assert_equal all_attributes, Item::OembedResponse.providable_all_attributes
end
end
end
end
context "A photo that includes OembedProvidable" do
setup do
@photo = Factory.create(:photo)
end
should "have an oembed_response object" do
assert @photo.oembed_response
end
should "have an oembed_max_dimensions object when maxheight and maxwidth are specified" do
maxheight = 400
maxwidth = 600
assert @photo.oembed_response(:maxheight => maxheight,
:maxwidth => maxwidth)
assert_equal maxheight, @photo.oembed_response.maxheight
assert_equal maxwidth, @photo.oembed_response.maxwidth
assert @photo.respond_to?(:oembed_max_dimensions)
assert_equal maxheight, @photo.oembed_max_dimensions[:height]
assert_equal maxwidth, @photo.oembed_max_dimensions[:width]
end
context "has an oembed_response and" do
setup do
@response = @photo.oembed_response
end
context "has required attribute that" do
should "be title" do
assert @response.title.present?
end
should "be version" do
assert @response.version.present?
end
should "be height" do
assert @response.height.present?
end
should "be width" do
assert @response.width.present?
end
should "be url" do
assert @response.url.present?
end
should "be provider_url" do
assert @response.provider_url.present?
end
should "be provider_name" do
assert @response.provider_name.present?
end
end
context "has can have optional attribute that" do
should "be author_name" do
@photo = Factory.create(:photo, :author_name => "Snappy")
assert @photo.oembed_response.author_name.present?
assert_equal "Snappy", @photo.oembed_response.author_name
end
should "be author_url" do
@photo = Factory.create(:photo, :author_url => "http://snapsnap.com")
assert @photo.oembed_response.author_url.present?
assert_equal "http://snapsnap.com", @photo.oembed_response.author_url
end
should "be thumbnail_url" do
@photo = Factory.create(:photo, :thumbnail_url => "http://snapsnap.com/thumb.jpg")
assert @photo.oembed_response.thumbnail_url.present?
assert_equal "http://snapsnap.com/thumb.jpg", @photo.oembed_response.thumbnail_url
end
should "be thumbnail_width" do
@photo = Factory.create(:photo, :thumbnail_width => 50)
assert @photo.oembed_response.thumbnail_width.present?
assert_equal 50, @photo.oembed_response.thumbnail_width
end
should "be thumbnail_height" do
@photo = Factory.create(:photo, :thumbnail_height => 50)
assert @photo.oembed_response.thumbnail_height.present?
assert_equal 50, @photo.oembed_response.thumbnail_height
end
end
context "when returning json" do
should "succeed" do
assert @response.as_json
assert !@response.to_json.to_s.include?(':null')
end
end
context "when returning xml" do
should "succeed" do
assert @response.to_xml
end
end
end
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/test/unit/oembed_provider_test.rb
|
<gh_stars>1-10
# -*- coding: utf-8 -*-
require 'test_helper'
class OembedProviderTest < ActiveSupport::TestCase
context "The OembedProvider object" do
should "be able to set and return its provider name" do
name = "Media Conglomerate International"
OembedProvider.provider_name = name
assert_equal OembedProvider.provider_name, name
end
should "be able to set and return its provider url" do
url = "http://example.com"
OembedProvider.provider_url = url
assert_equal OembedProvider.provider_url, url
end
should "be able to set and return its cache age" do
age = "1440"
OembedProvider.cache_age = age
assert_equal OembedProvider.cache_age, age
end
should "return version as 1.0 of oEmbed spec" do
assert_equal "1.0", OembedProvider.version
end
should "have an array of base attribute keys" do
base_attributes = [:provider_url,
:provider_name,
:cache_age,
:version]
assert_equal OembedProvider.base_attributes, base_attributes
end
should "have an array of optional attribute keys" do
optional_attributes = [:title,
:author_name,
:author_url,
:thumbnail_url,
:thumbnail_width,
:thumbnail_height]
assert_equal OembedProvider.optional_attributes, optional_attributes
end
should "have a hash of keyed by oembed type with required attribute keys" do
required_attributes = {
:photo => [:url, :width, :height],
:video => [:html, :width, :height],
:link => [],
:rich => [:html, :width, :height] }
assert_equal OembedProvider.required_attributes, required_attributes
end
should "have a hash of keyed by oembed type photo with required attribute keys" do
requires = [:url, :width, :height]
assert_equal OembedProvider.required_attributes[:photo], requires
end
should "have a hash of keyed by oembed type video with required attribute keys" do
requires = [:html, :width, :height]
assert_equal OembedProvider.required_attributes[:video], requires
end
should "have a hash of keyed by oembed type link with required attribute keys" do
requires = []
assert_equal OembedProvider.required_attributes[:link], requires
end
should "have a hash of keyed by oembed type rich with required attribute keys" do
requires = [:html, :width, :height]
assert_equal OembedProvider.required_attributes[:rich], requires
end
context "have an cattr accessor for mapping controllers that aren't tableized version of models, to their corresponding models" do
should "be able to set and read controller_model_maps" do
assert OembedProvider.respond_to?(:controller_model_maps)
assert_equal Hash.new, OembedProvider.controller_model_maps
test_hash = { :images => 'StillImage' }
OembedProvider.controller_model_maps = test_hash
assert_equal test_hash, OembedProvider.controller_model_maps
test_hash[:audio] = 'AudioRecording'
OembedProvider.controller_model_maps[:audio] = 'AudioRecording'
assert_equal test_hash, OembedProvider.controller_model_maps
end
end
should "be able to answer find_provided_from with provided object based on passed in url" do
@photo = Factory.create(:photo)
url = "http://example.com/photos/#{@photo.id}"
assert_equal @photo, OembedProvider.find_provided_from(url)
end
end
end
|
kete/oembed_provider
|
rails/init.rb
|
<reponame>kete/oembed_provider
require 'oembed_provider'
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/db/migrate/20110212022722_create_photos.rb
|
<filename>test/full_2_3_5_app_with_tests/db/migrate/20110212022722_create_photos.rb
class CreatePhotos < ActiveRecord::Migration
def self.up
create_table :photos do |t|
t.string :title, :url, :null => false
t.string :author_name, :author_url, :thumbnail_url
t.integer :width, :height, :null => false
t.integer :thumbnail_width, :thumbnail_height
t.timestamps
end
end
def self.down
drop_table :photos
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/app/models/photo.rb
|
class Photo < ActiveRecord::Base
include OembedProvidable
oembed_providable_as :photo
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/test/factories.rb
|
Factory.define :item do |f|
f.sequence(:label) { |n| "a label#{n}"}
f.sequence(:description) { |n| "a description#{n}"}
end
Factory.define :photo do |f|
f.sequence(:title) { |n| "a title#{n}"}
f.sequence(:url) { |n| "http://example.com/photo?id=#{n}"}
f.sequence(:width) { |n| "600"}
f.sequence(:height) { |n| "400"}
end
# f.sequence(:author_name) { |n| "an author_name#{n}"}
# f.sequence(:author_url) { |n| "http://example.com/author?id=#{n}"}
|
kete/oembed_provider
|
app/controllers/oembed_provider_controller.rb
|
<reponame>kete/oembed_provider
class OembedProviderController < ApplicationController
# Prevents the following error from showing up, common in Rails engines
# A copy of ApplicationController has been removed from the module tree but is still active!
unloadable
# GET /oembed?url=... json by default
# GET /oembed.json?url=...
# GET /oembed.json?url=...&callback=myCallback
# GET /oembed.xml?url=...
def endpoint
# get object that we want an oembed_response from
# based on url
# and get its oembed_response
media_item = OembedProvider.find_provided_from(params[:url])
options = Hash.new
max_dimensions = [:maxwidth, :maxheight]
unless media_item.class::OembedResponse.providable_oembed_type == :link
max_dimensions.each { |dimension| options[dimension] = params[dimension] if params[dimension].present? }
end
@oembed_response = media_item.oembed_response(options)
# to_xml and to_json overidden in oembed_providable module
# to be properly formatted
# TODO: handle unauthorized case
respond_to do |format|
if @oembed_response
format.html { render_json @oembed_response.to_json } # return json for default
format.json { render_json @oembed_response.to_json }
format.xml { render :xml => @oembed_response }
else
format.all { render_404 }
end
end
end
protected
# thanks to http://blogs.sitepoint.com/2006/10/05/json-p-output-with-rails/
def render_json(json, options={})
callback, variable = params[:callback], params[:variable]
response = begin
if callback && variable
"var #{variable} = #{json};\n#{callback}(#{variable});"
elsif variable
"var #{variable} = #{json};"
elsif callback
"#{callback}(#{json});"
else
json
end
end
render({:content_type => :js, :text => response}.merge(options))
end
end
|
kete/oembed_provider
|
lib/oembed_provider_helper.rb
|
# include this in your relevant helpers
# to add discoverability link, etc.
module OembedProviderHelper
# hardcodes http as protocol
# http is specified in http://oembed.com/
def oembed_provider_links
host_url = request.host
escaped_request_url = request.url.sub('://', '%3A//')
html = tag(:link, :rel => "alternate",
:type => "application/json+oembed",
:href => "http://#{host_url}/oembed?url=#{escaped_request_url}",
:title => "JSON oEmbed for #{@title}")
html += tag(:link, :rel => "alternate",
:type => "application/xml+oembed",
:href => "http://#{host_url}/oembed.xml?url=#{escaped_request_url}",
:title => "XML oEmbed for #{@title}")
end
end
|
kete/oembed_provider
|
test/full_2_3_5_app_with_tests/config/routes.rb
|
<gh_stars>1-10
ActionController::Routing::Routes.draw do |map|
map.resources :photos
map.resources :items
end
|
FatherofDharma/Palindrome
|
spec/pal_logic_spec.rb
|
require('rspec')
require('pal_logic')
describe('Palindrome') do
it("splits an even letter word in half and returns the first half")do
word1 = Palindrome.new()
word1.half("turtle")
expect(word1.first).to(eq(["t", "u", "r"]))
end
it("splits an even letter word in half and returns the last half reversed")do
word1 = Palindrome.new()
word1.half("turtle")
expect(word1.last).to(eq(["e", "l", "t"]))
end
it("splits an odd letter word in half and returns the first half")do
word1 = Palindrome.new()
word1.half("racecar")
expect(word1.last).to(eq(["r", "a", "c", "e"]))
end
it("splits an odd letter word in half and returns the last half reversed")do
word1 = Palindrome.new()
word1.half("racecar")
expect(word1.last).to(eq(["r", "a", "c", "e"]))
end
end
|
FatherofDharma/Palindrome
|
lib/pal_logic.rb
|
#!/usr/bin/ruby
require('pry')
class Palindrome
def initialize()
end
def half(word)
@word = word
@split_word = word.split("")
@first_half = []
@last_half = []
x = 0
y = @split_word.length - 1
if @split_word.length % 2 == 0
while (x < @split_word.length / 2)
@first_half.push(@split_word[x])
x += 1
end
until (y < @split_word.length / 2)
@last_half.push(@split_word[y])
y -= 1
end
else
while (x <= @split_word.length / 2)
@first_half.push(@split_word[x])
x += 1
end
until (y < @split_word.length / 2)
@last_half.push(@split_word[y])
y -= 1
end
end
def pal_check
if @first_half == @last_half
puts "Your word #{@word} is a palindrome!"
else
puts "Your word #{@word} is not a palindrome. :-("
end
end
end
def first
@first_half
end
def last
@last_half
end
end
puts "Enter a word: "
input = gets.chomp
word1 = Palindrome.new()
word1.half(input)
p word1.first
p word1.last
word1.pal_check
|
gibbs/puppet-login_defs
|
spec/classes/init_spec.rb
|
require 'spec_helper'
describe 'login_defs', type: :class do
context 'on supported systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) { facts }
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('login_defs') }
it { is_expected.to contain_class('login_defs') }
it {
is_expected.to create_file('/etc/login.defs').with({
owner: 'root',
group: 0,
mode: '0644'
})
}
end
end
end
end
|
gibbs/puppet-login_defs
|
spec/acceptance/options_spec.rb
|
<filename>spec/acceptance/options_spec.rb
require 'spec_helper_acceptance'
describe 'options' do
pp = <<-MANIFEST
class { 'login_defs':
options => {
'GID_MIN' => {
value => '2000',
},
'HUSHLOGIN_FILE' => {
value => '.hushlogin',
enabled => false,
},
'USERGROUPS_ENAB' => {
value => 'no',
},
'PASS_MAX_DAYS' => {
value => 123,
comment => 'testcomment',
},
'DEFAULT_HOME' => {
value => 'yes',
enabled => false,
},
}
}
MANIFEST
it 'applies idempotently' do
idempotent_apply(pp)
end
describe file('/etc/login.defs') do
it { is_expected.to exist }
it { is_expected.to be_file }
it { is_expected.to be_mode 6_44 }
it { is_expected.to be_owned_by 'root' }
it { is_expected.to be_readable }
its(:content) do
is_expected.to match(%r{MANAGED BY PUPPET})
# Custom
is_expected.to match(%r{GID_MIN 2000})
is_expected.to match(%r{#HUSHLOGIN_FILE .hushlogin})
is_expected.to match(%r{USERGROUPS_ENAB no})
is_expected.to match(%r{PASS_MAX_DAYS 123})
is_expected.to match(%r{# testcomment})
is_expected.to match(%r{#DEFAULT_HOME yes})
# Ensure a common value is correct
is_expected.to match(%r{ENCRYPT_METHOD SHA512})
end
end
end
|
gibbs/puppet-login_defs
|
spec/acceptance/init_spec.rb
|
<filename>spec/acceptance/init_spec.rb
require 'spec_helper_acceptance'
describe 'include class' do
pp = <<-MANIFEST
include ::login_defs
MANIFEST
it 'applies idempotently' do
idempotent_apply(pp)
end
describe file('/etc/login.defs') do
it { is_expected.to exist }
it { is_expected.to be_file }
it { is_expected.to be_mode 6_44 }
it { is_expected.to be_owned_by 'root' }
it { is_expected.to be_readable }
its(:content) { is_expected.to match(%r{MANAGED BY PUPPET}) }
end
end
|
flynnwastaken/seat-allocator
|
seat-allocator-2010.rb
|
# This hash holds the 2010 census apportionment populations of the fifty states,
# plus DC and Puerto Rico. This data is the default.
state_pops = {
"Alabama" => 4_802_982, "Alaska" => 721_523, "Arizona" => 6_412_700,
"Arkansas" => 2_926_229, "California" => 37_341_989, "Colorado" => 5_044_930,
"Connecticut" => 3_581_628, "Delaware" => 900_877,
"District of Columbia" => 604_598, "Florida" => 18_900_773,
"Georgia" => 9_727_566, "Hawaii" => 1_366_862, "Idaho" => 1_573_499,
"Illinois" => 12_865_380, "Indiana" => 6_501_582, "Iowa" => 3_053_787,
"Kansas" => 2_863_813, "Kentucky" => 4_350_606, "Louisiana" => 4_553_962,
"Maine" => 1_333_074, "Maryland" => 5_789_929, "Massachusetts" => 6_559_644,
"Michigan" => 9_911_626, "Minnesota" => 5_314_879, "Mississippi" => 2_978_240,
"Missouri" => 6_011_478, "Montana" => 994_416, "Nebraska" => 1_831_825,
"Nevada" => 2_709_432, "New Hampshire" => 1_321_445,
"New Jersey" => 8_807_501, "New Mexico" => 2_067_273,
"New York" => 19_421_055, "North Carolina" => 9_565_781,
"North Dakota" => 675_905, "Ohio" => 11_568_495, "Oklahoma" => 3_764_882,
"Oregon" => 3_848_606, "Pennsylvania" => 12_734_905,
"Puerto Rico" => 3_725_789, "Rhode Island" => 1_055_247,
"South Carolina" => 4_645_975, "South Dakota" => 819_761,
"Tennessee" => 6_375_431, "Texas" => 25_268_418, "Utah" => 2_770_765,
"Vermont" => 630_337, "Virginia" => 8_037_736, "Washington" => 6_753_369,
"West Virginia" => 1_859_815, "Wisconsin" => 5_698_230, "Wyoming" => 563_626
}
# According to legislation and the Constitution, all states start with 1 seat,
# and then the other seats are allocated.
current_seats = {
"Alabama" => 1, "Alaska" => 1, "Arizona" => 1, "Arkansas" => 1,
"California" => 1, "Colorado" => 1, "Connecticut" => 1, "Delaware" => 1,
"District of Columbia" => 1, "Florida" => 1, "Georgia" => 1, "Hawaii" => 1,
"Idaho" => 1, "Illinois" => 1, "Indiana" => 1, "Iowa" => 1, "Kansas" => 1,
"Kentucky" => 1, "Louisiana" => 1, "Maine" => 1, "Maryland" => 1,
"Massachusetts" => 1, "Michigan" => 1, "Minnesota" => 1, "Mississippi" => 1,
"Missouri" => 1, "Montana" => 1, "Nebraska" => 1, "Nevada" => 1,
"New Hampshire" => 1, "New Jersey" => 1, "New Mexico" => 1, "New York" => 1,
"North Carolina" => 1, "North Dakota" => 1, "Ohio" => 1, "Oklahoma" => 1,
"Oregon" => 1, "Pennsylvania" => 1, "Puerto Rico" => 1, "Rhode Island" => 1,
"South Carolina" => 1, "South Dakota" => 1, "Tennessee" => 1, "Texas" => 1,
"Utah" => 1, "Vermont" => 1, "Virginia" => 1, "Washington" => 1,
"West Virginia" => 1, "Wisconsin" => 1, "Wyoming" => 1
}
# This is dummy data that is replaced by the calculations in the code.
priority_number = {
"Alabama" => 1, "Alaska" => 1, "Arizona" => 1, "Arkansas" => 1,
"California" => 1, "Colorado" => 1, "Connecticut" => 1, "Delaware" => 1,
"District of Columbia" => 1, "Florida" => 1, "Georgia" => 1, "Hawaii" => 1,
"Idaho" => 1, "Illinois" => 1, "Indiana" => 1, "Iowa" => 1, "Kansas" => 1,
"Kentucky" => 1, "Louisiana" => 1, "Maine" => 1, "Maryland" => 1,
"Massachusetts" => 1, "Michigan" => 1, "Minnesota" => 1, "Mississippi" => 1,
"Missouri" => 1, "Montana" => 1, "Nebraska" => 1, "Nevada" => 1,
"New Hampshire" => 1, "New Jersey" => 1, "New Mexico" => 1, "New York" => 1,
"North Carolina" => 1, "North Dakota" => 1, "Ohio" => 1, "Oklahoma" => 1,
"Oregon" => 1, "Pennsylvania" => 1, "Puerto Rico" => 1, "Rhode Island" => 1,
"South Carolina" => 1, "South Dakota" => 1, "Tennessee" => 1, "Texas" => 1,
"Utah" => 1, "Vermont" => 1, "Virginia" => 1, "Washington" => 1,
"West Virginia" => 1, "Wisconsin" => 1, "Wyoming" => 1
}
# Some basic functions.
def die(x)
puts x
exit(1)
end
def prompt
print ">> "
end
# Querying the user for their preference
puts %q{
The population of the USA at the last census in 2010 was 308,745,538.
Do you wish to use this population and the 2010 state populations for House
of Representatives seat allocation, Y/N?
}
prompt
pop_query = $stdin.gets.chomp
if pop_query.downcase == "y"
population = 312_474_202.0
elsif pop_query.downcase == "n"
puts "\nPlease enter the total US population you wish to use."
prompt
population = $stdin.gets.chomp.to_f
# Iterates through the list of states, and overwrites the default 2010 census
# population with user input.
state_pops.each_key do |name|
puts "\nPlease enter the population of #{name} you wish to use."
prompt
new_state_pop = $stdin.gets.chomp.to_i
state_pops[name] = new_state_pop
puts "\nOkay, the population of #{name} is now #{new_state_pop}."
end
# User must manually confirm their data entry was correct.
puts "\nCheck if all these numbers are correct:\n\n"
puts state_pops
puts "\nAre they correct, Y/N?"
prompt
doublecheck = $stdin.gets.chomp
if doublecheck.downcase == "y"
puts "\nGreat!"
elsif doublecheck.downcase == "n"
puts "\nShoot."
die("\nI guess you'll have to start over.\n")
else
die("\nERROR 2: Sorry, what?? Start over.")
end
else
die("\nERROR 1: I'm sorry, that answer wasn't valid. Goodbye!\n")
end
# A query of whether the user wants to use a specific number of seats or use a
# specific representativeness of each seat
puts "Do you want to (1) enter a specific number of seats OR (2) enter the",
"number of people the average representative represents, 1 or 2?"
prompt
seatsquery = $stdin.gets.chomp.to_i
if seatsquery == 1
puts %q{
How many seats do you want the House to have?
Some interesting numbers:
435 (the current fixed number of seats by law)
554 (the "Wyoming Rule")
1_645 (Madisonian)
10_415 (Constitutional maximum)
}
prompt
seats = $stdin.gets.chomp.to_f.ceil
if seats < 52
die("I'm sorry, that's too few seats.")
elsif 10_416 < seats
die("I'm sorry, that's too many seats.")
end
repratio = (population / seats).round(0)
puts "\nThe US House of Representatives will have a total of #{seats}",
"seats, with the average Representative representing #{repratio} people."
puts
elsif seatsquery == 2
puts %q{
How many people does the average representative represent?
Some interesting numbers:
718_331 (the current average for 435 seats)
563_626 (the "Wyoming rule")
190_000 (Madisonian)
30_000 (Constitutional minimum
}
prompt
repratio = $stdin.gets.chomp.to_f.ceil
if repratio < 30_000
die("I'm sorry, that's too few people for a district.")
elsif 6_009_119 < repratio
die("I'm sorry, that's too many people for a district.")
end
# Calculating the number of seats.
seats = (population / repratio).round(0)
puts "\nThe US House of Representatives will have a total of #{seats}",
"seats, with the average Representative representing #{repratio} people."
puts
else
die("\nERROR 1: I'm sorry, that answer wasn't valid. Goodbye!\n")
end
seats_to_give_out = seats - 52
while seats_to_give_out > 0
# Takes each state and calculates a priority number for them, then orders them
# from largest priority number to smallest.
state_pops.each_key do |k|
priority_number[k] = state_pops[k] / Math.sqrt(current_seats[k] * (current_seats[k] + 1))
priority_number = priority_number.invert.sort { |a, b| b <=> a }.to_h.invert
end
# Takes the state name from the first position in the sorted priority number
# hash and assigns one seat to that state.
key = priority_number.keys[0]
current_seats[key] += 1
# This shows each step of the process as individual seats are assigned.
# Feel free to comment this out if you want less text displayed when you run
# the program.
# puts "#{key} now has #{current_seats[key]} seats."
seats_to_give_out -= 1
end
puts "\nThe final allocation of seats to states is:\n"
current_seats.each do |k, v|
puts "#{k}: #{v} seats."
end
puts "\nThank you for using \"Seat Allocator 2010\"."
|
landondao1/nginx
|
metadata.rb
|
name 'nginx'
maintainer '<NAME>, Inc.'
maintainer_email '<EMAIL>'
license 'Apache-2.0'
description 'Installs and configures nginx'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '8.1.6'
recipe 'nginx', 'Installs nginx package and sets up configuration with Debian apache style with sites-enabled/sites-available'
recipe 'nginx::source', 'Installs nginx from source and sets up configuration with Debian apache style with sites-enabled/sites-available'
depends 'build-essential', '>= 5.0'
depends 'ohai', '>= 4.1.0'
depends 'yum-epel'
depends 'zypper'
supports 'amazon'
supports 'centos'
supports 'debian'
supports 'fedora'
supports 'oracle'
supports 'redhat'
supports 'scientific'
supports 'ubuntu'
supports 'suse'
supports 'opensuse'
supports 'opensuseleap'
source_url 'https://github.com/chef-cookbooks/nginx'
issues_url 'https://github.com/chef-cookbooks/nginx/issues'
chef_version '>= 12.14' if respond_to?(:chef_version)
|
hugogzz93/graphql_ar
|
lib/graphql_relation_helper.rb
|
<reponame>hugogzz93/graphql_ar<gh_stars>0
# frozen_string_literal: true
module GraphqlRelationHelper
def has_many(relation)
model = relation.to_s.camelcase.singularize
field relation, ["Types::#{model}Type".constantize], null: false do
argument :query, "Types::#{model}QueryType".constantize, required: false
end
define_method relation do |req = nil|
if req
query = req[:query].to_h
query[:id] = query.delete(:ids) if query.key?(:ids)
end
if object
object.send(relation).where(query)
else
model.constantize.where(query)
end
end
end
def belongs_to(name)
field name, "Types::#{name.to_s.capitalize}Type".constantize, null: false
define_method name do |query: nil|
object.send(name)
end
end
end
|
hugogzz93/graphql_ar
|
graphql_ar.gemspec
|
Gem::Specification.new do |s|
s.name = 'graphql_ar'
s.version = '0.0.0'
s.date = '2019-11-07'
s.summary = 'Helps integrate graphql with active record'
s.authors = '<NAME>'
s.email = '<EMAIL>'
s.files = ['lib/graphql_ar.rb','lib/graphql_mutation.rb', 'lib/graphql_relation_helper.rb']
s.add_runtime_dependency 'graphql'
s.add_runtime_dependency 'activesupport'
end
|
hugogzz93/graphql_ar
|
lib/graphql_mutation.rb
|
<gh_stars>0
# frozen_string_literal: true
require 'active_support/concern'
# Usage:
# class UserOps < GraphQL::Schema::Object
# include GraphqlMutation
# is_mutation_of User
#
# ...any overwrites here
# end
#
# or inline
#
# UserOps = GraphqlMutation.create_ops_for User
module GraphqlMutation
extend ActiveSupport::Concern
def self.create_ops_for(model)
Class.new(GraphQL::Schema::Object) do
include GraphqlMutation
is_mutation_of model
end
end
included do
def self.is_mutation_of(model)
create = proc do |_, args, _ctx|
model.create! args.input.to_h
end
update = proc do |instance, args, _ctx|
instance.update! args.input.to_h
instance.reload
end
destroy = proc do |instance|
instance.destroy!
instance.id
rescue Exception => e
nil
end
class_eval do
@model = model
field :create, "Types::#{model.name}Type", null: false,
resolve: create do
argument :input, "Types::#{model.name}InputType", required: true
end
field :update, "Types::#{model.name}Type", null: false,
resolve: update do
argument :input, "Types::#{model.name}InputType", required: true
end
field :destroy, GraphQL::Types::ID, null: true, resolve: destroy
end
end
# def self.for(belongs_to, as:)
# relation = as
# model = @model
# klass = Class.new(self) do
# create = proc do |_, args, _ctx|
# debugger
# belongs_to.send(relation).create(args.to_h)
# end
#
# field :create, "Types::#{model.name}Type", null: false, resolve: create do
# argument :input, "Types::#{model.name}InputType", required: false
# end
# end
#
# return klass
# end
#
# def self.has_many(relation)
# # NOTE: relation can't be inlined, it needs to be saved in a file
# self.class_eval do
# model = relation.to_s.camelcase.singularize
# relationOps = "Mutations::#{model}Ops".constantize
#
# resolver = proc do |object, args, ctx|
# if(args["id"])
# object.send(relation).find_by(args.to_h)
# else
# relationOps.for(object, as: relation)
# end
# end
#
# field relation, "Mutations::#{model}Ops", null: false,
# resolve: resolver do
# argument :id, GraphQL::Types::ID, required: false
# end
# end
# end
end
end
|
hugogzz93/graphql_ar
|
lib/graphql_ar.rb
|
require 'GraphqlRelationHelper'
require 'GraphqlMutation'
module GraphqlAr
def self.GraphqlRelationHelper
GraphqlRelationHelper
end
def self.GraphqlMutation
GraphqlMutation
end
end
|
garrylachman/chef-ultimate-config-cookbook
|
attributes/default.rb
|
# Cookbook:: ultimate_config_cookbook
#
# The MIT License (MIT)
#
# Copyright:: 2017, <NAME>
# https://github.com/garrylachman/chef-ultimate-config-cookbook
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
default['config1']['sec1']['garry'] = 'lachman'
default['config1']['sec1']['lachman'] = 'garry'
default['config1']['sec2']['lachman1'] = '1garry'
default['config2']['garry'] = 'lachman'
default['config2']['lachman'] = 'garry'
|
garrylachman/chef-ultimate-config-cookbook
|
recipes/yaml_example.rb
|
# Cookbook:: ultimate_config_cookbook
#
# The MIT License (MIT)
#
# Copyright:: 2017, <NAME>
# https://github.com/garrylachman/chef-ultimate-config-cookbook
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
yaml_file '/tmp/4.yaml' do action :delete end
yaml_file '/tmp/5.yaml' do action :delete end
yaml_file '/tmp/6.yaml' do action :delete end
yaml_file '/tmp/4.yaml' do
file_content node.default['config1']
action :create
end
edit_content = {
"integer" => 1,
"float" => 3.14159,
"true" => true,
"false" => false,
"string" => "hi",
"array" => [[1], [2], [3]],
"key" => {
"group" => {
"value" => "lol"
}
}
}
yaml_file '/tmp/4.yaml' do
file_content edit_content
action :edit
end
yaml_file '/tmp/5.yaml' do
file_content node.default['config1']
action :create_or_edit
end
yaml_file '/tmp/6.yaml' do
file_content edit_content
action :create_or_edit
end
yaml_file '/tmp/6.yaml' do
action :delete
end
yaml_file '/tmp/5.yaml' do
file_content edit_content
action :replace
end
|
garrylachman/chef-ultimate-config-cookbook
|
resources/json_file.rb
|
<reponame>garrylachman/chef-ultimate-config-cookbook<filename>resources/json_file.rb
# Cookbook:: ultimate_config_cookbook
#
# The MIT License (MIT)
#
# Copyright:: 2017, <NAME>
# https://github.com/garrylachman/chef-ultimate-config-cookbook
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
resource_name :json_file
property :file_path, String, name_property: true
property :file_content, Hash, {}
require 'json/ext'
class ::Hash
def deep_merge(second)
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
self.merge(second, &merger)
end
end
action :create do
if not ::File.exist?(new_resource.file_path)
json_file = ::File.new(new_resource.file_path, "w")
json_file.puts new_resource.file_content.to_json
json_file.close
end
end
action :edit do
if ::File.exist?(new_resource.file_path)
json_file = ::File.open(new_resource.file_path, "r+")
current_content = {}
begin
current_content = JSON.parse(json_file.read())
rescue JSON::ParserError => e
end
new_content = current_content.deep_merge(new_resource.file_content)
json_file.truncate(0)
json_file.puts new_content.to_json
json_file.close
end
end
action :create_or_edit do
action_create
action_edit
end
action :delete do
if ::File.exist?(new_resource.file_path)
::File.delete(new_resource.file_path)
end
end
action :replace do
action_delete
action_create
end
|
garrylachman/chef-ultimate-config-cookbook
|
resources/ini_file.rb
|
# Cookbook:: ultimate_config_cookbook
#
# The MIT License (MIT)
#
# Copyright:: 2017, <NAME>
# https://github.com/garrylachman/chef-ultimate-config-cookbook
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
resource_name :ini_file
property :file_path, String, name_property: true
property :file_content, Hash, {}
require 'inifile'
action :create do
if not ::File.exist?(new_resource.file_path)
ini_file = IniFile.new(:filename => new_resource.file_path, :content => new_resource.file_content)
ini_file.save
end
end
action :edit do
if ::File.exist?(new_resource.file_path)
ini_file = IniFile.load(new_resource.file_path)
ini_file = ini_file.merge(new_resource.file_content)
ini_file.save
end
end
action :create_or_edit do
action_create
action_edit
end
action :delete do
if ::File.exist?(new_resource.file_path)
::File.delete(new_resource.file_path)
end
end
action :replace do
action_delete
action_create
end
|
jayzz55/ingress
|
lib/ingress.rb
|
<gh_stars>1-10
require "ingress/version"
require "ingress/permissions"
|
jayzz55/ingress
|
lib/ingress/permissions.rb
|
require "ingress/permissions_repository"
require "ingress/copy_permissions_repository_into_role"
require "ingress/build_permissions_repository_for_role"
module Ingress
class Permissions
class << self
def permissions_repository
@permissions_repository ||= PermissionsRepository.new
end
def inherits(permissions_class)
role_identifier = :dummy
if permissions_class
@permissions_repository = permissions_repository.merge(
Services::CopyPermissionsRepositoryIntoRole.perform(role_identifier, permissions_class.permissions_repository),
)
end
end
def define_role_permissions(role_identifier = nil, permissions_class = nil, &block)
if role_identifier.nil?
role_identifier = :dummy
end
if permissions_class
@permissions_repository = permissions_repository.merge(
Services::CopyPermissionsRepositoryIntoRole.perform(role_identifier, permissions_class.permissions_repository),
)
end
if block_given?
@permissions_repository = permissions_repository.merge(Services::BuildPermissionsRepositoryForRole.perform(role_identifier, &block))
end
end
end
attr_reader :user
def initialize(user)
@user = user
end
def can?(action, subject, options = {})
user_role_identifiers.any? do |role_identifier|
rules = self.class.permissions_repository.rules_for(role_identifier, action, subject)
cannot_match = rules.reject(&:allows?).any? do |rule|
rule.match?(action, subject, user, options)
end
break false if cannot_match
rules.select(&:allows?).any? do |rule|
rule.match?(action, subject, user, options)
end
end
end
def user_role_identifiers
[]
end
end
end
|
jayzz55/ingress
|
spec/ingress_spec.rb
|
<reponame>jayzz55/ingress
require "spec_helper"
require "securerandom"
RSpec.describe Ingress do
class TestUser
attr_reader :id, :role_identifiers, :disabled
def initialize(id: nil, role_identifiers: [], disabled: false)
@id = id
@role_identifiers = role_identifiers
@disabled = disabled
end
end
class TestObject
attr_reader :id, :user_id, :read_only
def initialize(id: nil, user_id: nil, read_only: false)
@id = id
@user_id = user_id
@read_only = read_only
end
end
describe "when user has no role", uuid: SecureRandom.uuid do
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions(:member) do
can "*", "*"
end
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: []) }
let(:permissions) { user_permissions_class.new(user) }
it "user is not able to do anything" do
expect(permissions.can?(:create, :member_stuff)).to be_falsy
end
end
describe "when user has single role" do
let(:member_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can :create, :member_stuff
can :create, TestObject
can :destroy, TestObject
can :update, TestObject, if: -> (user, object) { user.id == object.user_id }
cannot %i[update destroy], TestObject, if: -> (user, object) { object.read_only }
cannot '*', '*', if: -> (user, _object) { user.disabled }
end
end
end
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions :member, MemberPermissions
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: [:member]) }
let(:permissions) { user_permissions_class.new(user) }
before do
MemberPermissions = member_permissions_class
end
after do
Object.send(:remove_const, :MemberPermissions)
end
it "user is able to do basic action defined for role" do
expect(permissions.can?(:create, :member_stuff)).to be_truthy
end
it "user is not able to things not defined for role" do
expect(permissions.can?(:show, :member_stuff)).to be_falsy
end
context "for permissions defined with class" do
let(:test_object) { TestObject.new }
it "user is able to do basic action defined for role" do
expect(permissions.can?(:create, test_object)).to be_truthy
expect(permissions.can?(:destroy, test_object)).to be_truthy
end
end
context "for permissions defined with class with conditions" do
let(:test_object) { TestObject.new }
context "when conditions won't match" do
let(:user) { TestUser.new(id: 5, role_identifiers: [:member]) }
let(:test_object) { TestObject.new(id: 88, user_id: 4) }
it "user is not able to do action defined for role" do
expect(permissions.can?(:update, test_object)).to be_falsy
end
end
context "when conditions will match" do
let(:user) { TestUser.new(id: 5, role_identifiers: [:member]) }
let(:test_object) { TestObject.new(id: 88, user_id: 5) }
it "user is able to do action defined for role", :aggregate_failures do
expect(permissions.can?(:update, test_object)).to be_truthy
expect(permissions.can?(:create, :member_stuff)).to be_truthy
expect(permissions.can?(:create, TestObject)).to be_truthy
end
end
context "when cannot conditions will match" do
let(:user) { TestUser.new(id: 5, role_identifiers: [:member], disabled: true) }
let(:test_object) { TestObject.new(id: 88, user_id: 5, read_only: true) }
it "user is not able to do action defined for role", :aggregate_failures do
expect(permissions.can?(:update, test_object)).to be_falsy
expect(permissions.can?(:create, :member_stuff)).to be_falsy
expect(permissions.can?(:create, TestObject)).to be_falsy
end
end
context "when class is given instead of instance" do
it "should fail but shouldn't error" do
expect(permissions.can?(:update, TestObject)).to be_falsy
end
end
end
end
describe "when user has 2 roles that have permissions defined for them" do
let(:member_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can :create, :member_stuff
end
end
end
let(:subscriber_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can :create, :subscriber_stuff
end
end
end
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions :member, MemberPermissions
define_role_permissions :subscriber, SubscriberPermissions
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: [:member, :subscriber]) }
let(:permissions) { user_permissions_class.new(user) }
before do
MemberPermissions = member_permissions_class
SubscriberPermissions = subscriber_permissions_class
end
after do
Object.send(:remove_const, :MemberPermissions)
Object.send(:remove_const, :SubscriberPermissions)
end
it "user is able to do things defined in both roles" do
expect(permissions.can?(:create, :member_stuff)).to be_truthy
expect(permissions.can?(:create, :subscriber_stuff)).to be_truthy
end
end
describe "when user has role that inherits all permissions from another role" do
let(:member_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can :create, :member_stuff
can :create, TestObject
end
end
end
let(:special_member_permissions_class) do
Class.new(Ingress::Permissions) do
inherits MemberPermissions
define_role_permissions do
can :locate, TestObject
cannot :create, :member_stuff
end
end
end
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions :member, MemberPermissions
define_role_permissions :special_member, SpecialMemberPermissions
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: [:special_member]) }
let(:permissions) { user_permissions_class.new(user) }
let(:test_object) { TestObject.new }
before do
MemberPermissions = member_permissions_class
SpecialMemberPermissions = special_member_permissions_class
end
after do
Object.send(:remove_const, :MemberPermissions)
Object.send(:remove_const, :SpecialMemberPermissions)
end
it "user is able to do basic action defined for role" do
expect(permissions.can?(:create, test_object)).to be_truthy
end
it "user is able to do things defined only for the new role" do
expect(permissions.can?(:locate, test_object)).to be_truthy
end
it "user is not able to do things that are taken away for the new role" do
expect(permissions.can?(:create, :member_stuff)).to be_falsy
end
context "and user has 2 roles and one has permissions that are taken away by another" do
let(:user) { TestUser.new(id: 5, role_identifiers: [:member, :special_member]) }
it "user is able to do things that are taken away by one of the roles" do
expect(permissions.can?(:create, :member_stuff)).to be_truthy
end
end
end
describe "when user has role that role allows everything" do
let(:admin_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can "*", "*"
end
end
end
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions :admin, AdminPermissions
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: [:admin]) }
let(:permissions) { user_permissions_class.new(user) }
let(:test_object) { TestObject.new }
before do
AdminPermissions = admin_permissions_class
end
after do
Object.send(:remove_const, :AdminPermissions)
end
it "user is able to do anything" do
expect(permissions.can?(:foobar, :wodget)).to be_truthy
expect(permissions.can?(:create, test_object)).to be_truthy
end
end
describe "when user has role which inherits from a role that allows everything and takes away a permission" do
let(:admin_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can "*", "*"
end
end
end
let(:limited_admin_permissions_class) do
Class.new(Ingress::Permissions) do
inherits AdminPermissions
define_role_permissions do
cannot :create, :wodget
end
end
end
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions :admin, AdminPermissions
define_role_permissions :limited_admin, LimitedAdminPermissions
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: [:limited_admin]) }
let(:permissions) { user_permissions_class.new(user) }
let(:test_object) { TestObject.new }
before do
AdminPermissions = admin_permissions_class
LimitedAdminPermissions = limited_admin_permissions_class
end
after do
Object.send(:remove_const, :AdminPermissions)
Object.send(:remove_const, :LimitedAdminPermissions)
end
it "user is not able to do the thing that was taken away" do
expect(permissions.can?(:create, :wodget)).to be_falsy
end
it "user is able to do anything else" do
expect(permissions.can?(:foobar, :wodget)).to be_truthy
expect(permissions.can?(:create, test_object)).to be_truthy
end
end
describe "when user has role that allows a specific action on anything" do
let(:member_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can :create, "*"
can :destroy, "*", if: -> (user, record) { record == TestObject || record.kind_of?(TestObject) }
end
end
end
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions :member, MemberPermissions
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: [:member]) }
let(:permissions) { user_permissions_class.new(user) }
let(:test_object) { TestObject.new }
before do
MemberPermissions = member_permissions_class
end
after do
Object.send(:remove_const, :MemberPermissions)
end
it "user is able to do that action on anything" do
expect(permissions.can?(:create, :wodget)).to be_truthy
expect(permissions.can?(:create, test_object)).to be_truthy
end
it "user is not able to do another action on anything" do
expect(permissions.can?(:foo, :wodget)).to be_falsy
end
context "with a condition" do
it "user is able to do that action on anything where the condition is met" do
expect(permissions.can?(:destroy, TestObject)).to be_truthy
expect(permissions.can?(:destroy, test_object)).to be_truthy
end
it "user is not able to do that action on things where the condition is not met" do
expect(permissions.can?(:destroy, :wodget)).to be_falsy
end
end
end
describe "when user has role that allows any action on a specific thing" do
let(:member_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions do
can "*", :wodget
can "*", TestObject, if: -> (user, record) { record.kind_of?(TestObject) && record.id == 5 }
can "*", :with_if_style, if: -> (user, record) { record.kind_of?(TestObject) && record.id == 5 }
can "*", :with_block do |user, record|
record.kind_of?(TestObject) && record.id == 5
end
end
end
end
let(:user_permissions_class) do
Class.new(Ingress::Permissions) do
define_role_permissions :member, MemberPermissions
def user_role_identifiers
user.role_identifiers
end
end
end
let(:user) { TestUser.new(id: 5, role_identifiers: [:member]) }
let(:permissions) { user_permissions_class.new(user) }
let(:test_object) { TestObject.new }
before do
MemberPermissions = member_permissions_class
end
after do
Object.send(:remove_const, :MemberPermissions)
end
it "user is able to do any action on that thing" do
expect(permissions.can?(:foo, :wodget)).to be_truthy
expect(permissions.can?(:bar, :wodget)).to be_truthy
end
it "user is not able to do any action on another thing" do
expect(permissions.can?(:foo, :bazzer)).to be_falsy
end
context "with a condition" do
it "user is able to do any action on a thing where the condition is met" do
expect(permissions.can?(:foo, TestObject.new(id: 5))).to be_truthy
expect(permissions.can?(:bar, TestObject.new(id: 5))).to be_truthy
end
it "user is not able to do any action on a thing where the condition is not met" do
expect(permissions.can?(:foo, TestObject.new(id: 4))).to be_falsy
end
it "should be able to do action if Class is provided" do
expect(permissions.can?(:with_block, TestObject)).to be_truthy
end
end
context "differing styles of defining conditions" do
it "permits when defined with an if: condition" do
expect(permissions.can?(:with_if_style, TestObject.new(id: 5))).to be_truthy
end
it "permits when defined with a block condition" do
expect(permissions.can?(:with_block, TestObject.new(id: 5))).to be_truthy
end
it "denies when defined with an if: condition" do
expect(permissions.can?(:with_if_style, TestObject.new(id: 4))).to be_falsy
end
it "denies when defined with a block condition" do
expect(permissions.can?(:with_block, TestObject.new(id: 4))).to be_falsy
end
end
end
end
|
jayzz55/ingress
|
lib/ingress/copy_permissions_repository_into_role.rb
|
require "ingress/permissions_repository"
module Ingress
module Services
class CopyPermissionsRepositoryIntoRole
class << self
def perform(role_identifier, template_permission_repository)
permission_repository = PermissionsRepository.new
permission_repository.copy_to_role(role_identifier, template_permission_repository)
permission_repository
end
end
end
end
end
|
jayzz55/ingress
|
lib/ingress/permissions_dsl.rb
|
<reponame>jayzz55/ingress
require "ingress/permissions_repository"
module Ingress
class PermissionsDsl
attr_reader :role_identifier, :permission_repository
def initialize(role_identifier)
@role_identifier = role_identifier
@permission_repository = PermissionsRepository.new
end
def can_do_anything
permission_repository.add_permission(role_identifier, true, "*", "*")
end
def can(actions, subjects, options = {}, &block)
for_each_action_and_subject(actions, subjects) do |action, subject|
condition = condition_from_options(options, block)
permission_repository.add_permission(role_identifier, true, action, subject, condition)
end
end
def cannot(actions, subjects, options = {}, &block)
for_each_action_and_subject(actions, subjects) do |action, subject|
condition = condition_from_options(options, block)
permission_repository.add_permission(role_identifier, false, action, subject, condition)
end
end
private
def for_each_action_and_subject(actions, subjects)
return unless block_given?
actions = [actions].flatten
subjects = [subjects].flatten
actions.each do |action|
subjects.each do |subject|
yield(action, subject)
end
end
end
def condition_from_options(options, block)
if_condition = options[:if] || block
if_condition.respond_to?(:call) ? if_condition : nil
end
end
end
|
jayzz55/ingress
|
lib/ingress/permissions_repository.rb
|
require "ingress/permission_rule"
module Ingress
class PermissionsRepository
attr_reader :role_rules
def initialize
@role_rules = Hashes.role_rules
@role_subject_action_rule = Hashes.role_subject_action_rule
end
def add_permission(role_identifier, allow, action, subject, conditions = nil)
rule = PermissionRule.new(allows: allow, action: action, subject: subject, conditions: conditions)
add_rule(role_identifier, rule)
end
def rules_for(role_identifier, action, subject)
rules = []
rules += find_rules(role_identifier, action, subject)
rules += find_rules(role_identifier, "*", "*")
rules += find_rules(role_identifier, action, "*")
rules += find_rules(role_identifier, "*", subject)
rules
end
def merge(permission_repository)
permission_repository.role_rules.each_pair do |role_identifier, rules|
rules.each do |rule|
add_rule(role_identifier, rule)
end
end
self
end
def copy_to_role(role_identifier, permission_repository)
permission_repository.role_rules.each_pair do |_, rules|
rules.each do |rule|
add_rule(role_identifier, rule)
end
end
self
end
private
def find_rules(role_identifier, action, subject)
rules = []
rules += @role_subject_action_rule[role_identifier][subject][action]
unless subject == "*"
rules += @role_subject_action_rule[role_identifier][subject.class][action]
end
rules
end
def add_rule(role_identifier, rule)
@role_rules[role_identifier] << rule
@role_subject_action_rule[role_identifier][rule.subject][rule.action] << rule
end
# creates hashes with the default values required in
# PermissionsRepository's constructor
module Hashes
module_function
# Three level deep hash returning an array
def role_subject_action_rule
Hash.new do |hash1, key1|
hash1[key1] = Hash.new do |hash2, key2|
hash2[key2] = Hash.new do |hash3, key3|
hash3[key3] = []
end
end
end
end
# One level deep hash returning an array
def role_rules
Hash.new { |hash, key| hash[key] = [] }
end
end
end
end
|
jayzz55/ingress
|
lib/ingress/build_permissions_repository_for_role.rb
|
<reponame>jayzz55/ingress
require "ingress/permissions_dsl"
module Ingress
module Services
class BuildPermissionsRepositoryForRole
class << self
def perform(role_identifier, &block)
permissions_dsl = PermissionsDsl.new(role_identifier)
permissions_dsl.instance_eval(&block)
permissions_dsl.permission_repository
end
end
end
end
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/unscope_where.rb
|
# frozen_string_literal: true
require 'rails_compatibility/active_record'
class << RailsCompatibility
if GTE_RAILS_4_0
def unscope_where(relation)
relation.unscope(:where)
end
else
def unscope_where(relation)
relation.dup.tap{|s| s.where_values = [] }
end
end
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/attribute_types.rb
|
# frozen_string_literal: true
require 'rails_compatibility'
require 'rails_compatibility/active_record'
class << RailsCompatibility
if ActiveRecord::Base.respond_to?(:attribute_types) # column_types was changed to attribute_types in Rails 5
def attribute_types(klass)
klass.attribute_types
end
elsif ActiveRecord::Base.respond_to?(:column_types) # Rails 4
def attribute_types(klass)
klass.column_types
end
else # In Rails 3
def attribute_types(klass)
klass.columns_hash
end
end
end
|
khiav223577/rails_compatibility
|
test/apply_join_dependency_test.rb
|
require 'test_helper'
require 'rails_compatibility/apply_join_dependency'
class ApplyJoinDependencyTest < Minitest::Test
def setup
skip if ActiveRecord::VERSION::MAJOR < 4 # Rails 3's includes + pluck will not become left outer joins
@posts = Post.includes(:user)
end
def test_not_become_immutable
RailsCompatibility.apply_join_dependency(@posts)
assert_equal false, @posts.where!(id: nil).exists?
end
def test_pluck_with_includes
assert_equal 'SELECT "posts".* FROM "posts"', @posts.to_sql
@posts = RailsCompatibility.apply_join_dependency(@posts)
assert_equal 'SELECT "posts".* FROM "posts" LEFT OUTER JOIN "users" ON "users"."id" = "posts"."user_id"', @posts.to_sql
end
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/has_include.rb
|
# frozen_string_literal: true
require 'rails_compatibility'
require 'rails_compatibility/active_record'
class << RailsCompatibility
if GTE_RAILS_6_1
def has_include?(relation, column_name)
relation.send(:has_include?, column_name)
end
elsif GTE_RAILS_5_0
def has_include?(relation, column_name)
relation.dup.send(:has_include?, column_name)
end
else
def has_include?(relation, column_name)
relation.send(:has_include?, column_name)
end
end
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility.rb
|
<filename>lib/rails_compatibility.rb<gh_stars>1-10
require 'rails_compatibility/version'
|
khiav223577/rails_compatibility
|
test/build_joins_test.rb
|
require 'test_helper'
require 'rails_compatibility/build_joins'
class BuildJoinsTest < Minitest::Test
def setup
@county_ids = County.all.map{|s| [s.name, s.id] }.to_h
@zipcode_ids = Zipcode.all.map{|s| [s.zip, s.id] }.to_h
end
def test_when_many_models_mapping_to_one
reflect = County.reflect_on_association(:zipcodes)
relation = Zipcode.where(zip: '30301')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [@county_ids['Fulton']], relation.pluck('counties_zipcodes.county_id')
relation = Zipcode.where(zip: '30291')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [@county_ids['Fulton']], relation.pluck('counties_zipcodes.county_id')
relation = Zipcode.where(zip: '55410')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [@county_ids['Hennepin']], relation.pluck('counties_zipcodes.county_id')
relation = Zipcode.where(zip: '55416')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [@county_ids['Hennepin']], relation.pluck('counties_zipcodes.county_id')
relation = Zipcode.where(zip: '!INVALID!')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [], relation.pluck('counties_zipcodes.county_id')
end
def test_many_when_one_models_mapping_to_many
reflect = Zipcode.reflect_on_association(:counties)
relation = County.where(name: 'Fulton')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [@zipcode_ids['30301'], @zipcode_ids['30291']], relation.pluck('counties_zipcodes.zipcode_id')
relation = County.where(name: 'Hennepin')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [@zipcode_ids['55410'], @zipcode_ids['55416']], relation.pluck('counties_zipcodes.zipcode_id')
relation = County.where(name: '!INVALID!')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal [], relation.pluck('counties_zipcodes.zipcode_id')
end
def test_custom_association_name
skip if ActiveRecord::VERSION::MAJOR < 4 # Rails 3 doesn't support inverse_of options in HABTM
reflect = TrainingProvider.reflect_on_association(:borrower_training_programs)
relation = TrainingProgram.where(name: 'program A')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal relation.ids, relation.pluck('training_programs_training_providers.training_program_id')
end
def test_custom_inverse_association_name
skip if ActiveRecord::VERSION::MAJOR < 4 # Rails 3 doesn't support inverse_of options in HABTM
reflect = TrainingProgram.reflect_on_association(:training_providers)
relation = TrainingProvider.where(name: 'provider X')
relation = relation.joins(RailsCompatibility.build_joins(reflect, relation)[0])
assert_equal relation.ids, relation.pluck('training_programs_training_providers.training_provider_id')
end
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/active_record.rb
|
# frozen_string_literal: true
require 'rails_compatibility'
require 'active_record'
class << RailsCompatibility
GTE_RAILS_6_1 = Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('6.1.0')
GTE_RAILS_6_0 = Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('6.0.0')
GTE_RAILS_5_2 = Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('5.2.0')
GTE_RAILS_5_1 = Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('5.1.0')
GTE_RAILS_5_0 = Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('5.0.0')
GTE_RAILS_4_0 = Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('4.0.0')
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/build_joins.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'rails_compatibility'
require 'rails_compatibility/construct_join_dependency'
require 'rails_compatibility/active_record'
class << RailsCompatibility
if GTE_RAILS_6_1
def build_joins(reflect, relation)
join_dependency = construct_join_dependency(reflect, relation)
joins = join_dependency.join_constraints([], relation.alias_tracker, relation.references_values)
return joins
end
elsif GTE_RAILS_6_0
def build_joins(reflect, relation)
join_dependency = construct_join_dependency(reflect, relation)
joins = join_dependency.join_constraints([], relation.alias_tracker)
return joins
end
elsif GTE_RAILS_5_2
def build_joins(reflect, relation)
join_dependency = construct_join_dependency(reflect, relation)
joins = join_dependency.join_constraints([], Arel::Nodes::InnerJoin, relation.alias_tracker)
return joins
end
elsif GTE_RAILS_5_0
def build_joins(reflect, relation)
join_dependency = construct_join_dependency(reflect, relation)
info = join_dependency.join_constraints([], Arel::Nodes::InnerJoin)[0]
return info.joins
end
elsif GTE_RAILS_4_0
def build_joins(reflect, relation)
join_dependency = construct_join_dependency(reflect, relation)
info = join_dependency.join_constraints([])[0]
return info.joins
end
else
def build_joins(reflect, relation)
join_dependency = construct_join_dependency(reflect, relation)
return join_dependency.join_associations
end
end
end
|
khiav223577/rails_compatibility
|
test/lib/seeds.rb
|
ActiveRecord::Schema.define do
self.verbose = false
create_table :users, force: true do |t|
t.string :name
t.string :email
t.string :gender
end
create_table :posts, force: true do |t|
t.references :user
t.string :title
end
create_table :counties, force: true do |t|
t.string :name, null: false
end
create_table :counties_zipcodes, force: true do |t|
t.references :county, index: true, null: false
t.references :zipcode, index: true, null: false
end
create_table :zipcodes, force: true do |t|
t.string :zip, null: false
t.string :city, null: false
end
create_table :training_programs, force: :cascade do |t|
t.string :name
end
create_table :training_providers, force: :cascade do |t|
t.string :name
end
create_table :training_programs_training_providers, id: false, force: :cascade do |t|
t.references :training_provider, null: false, index: false
t.references :training_program, null: false, index: false
end
end
ActiveSupport::Dependencies.autoload_paths << File.expand_path('../models/', __FILE__)
users = User.create!([
{ name: 'Peter', email: '<EMAIL>', gender: 'male' },
{ name: 'Pearl', email: '<EMAIL>', gender: 'female' },
{ name: 'Doggy', email: '<EMAIL>', gender: 'female' },
{ name: 'Catty', email: '<EMAIL>', gender: 'female' },
])
Post.create!(user: users[0])
County.create!([
{
name: 'Fulton',
zipcodes: [
Zipcode.new(city: 'Atlanta', zip: '30301'),
Zipcode.new(city: 'Union City', zip: '30291'),
],
},
{
name: 'Hennepin',
zipcodes: [
Zipcode.new(city: 'Minneapolis', zip: '55410'),
Zipcode.new(city: 'Edina', zip: '55416'),
],
},
])
if ActiveRecord::VERSION::MAJOR > 3 # Rails 3 doesn't support inverse_of options in HABTM
TrainingProgram.create!(
name: 'program A',
training_providers: [
TrainingProvider.create!(name: 'provider X'),
],
)
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/apply_join_dependency.rb
|
# frozen_string_literal: true
require 'rails_compatibility'
require 'rails_compatibility/active_record'
class << RailsCompatibility
if GTE_RAILS_5_2
def apply_join_dependency(relation)
relation.send(:apply_join_dependency)
end
elsif GTE_RAILS_5_1
def apply_join_dependency(relation)
relation.send(:construct_relation_for_association_calculations)
end
elsif GTE_RAILS_5_0
def apply_join_dependency(relation)
relation.dup.send(:construct_relation_for_association_calculations)
end
else
def apply_join_dependency(relation)
relation.send(:construct_relation_for_association_calculations)
end
end
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/construct_join_dependency.rb
|
<filename>lib/rails_compatibility/construct_join_dependency.rb
# frozen_string_literal: true
require 'rails_compatibility'
require 'rails_compatibility/active_record'
class << RailsCompatibility
if GTE_RAILS_6_0
def construct_join_dependency(reflect, relation)
joins = inverse_association_joins(reflect)
return relation.construct_join_dependency(joins, Arel::Nodes::InnerJoin)
end
elsif GTE_RAILS_5_2
def construct_join_dependency(reflect, relation)
joins = inverse_association_joins(reflect)
join_dependency = ActiveRecord::Associations::JoinDependency.new(reflect.klass, relation.table, joins)
root = join_dependency.send(:join_root)
join_dependency.instance_variable_set(:@alias_tracker, relation.alias_tracker)
join_dependency.send(:construct_tables!, root)
return join_dependency
end
else
def construct_join_dependency(reflect, _relation)
joins = inverse_association_joins(reflect)
return ActiveRecord::Associations::JoinDependency.new(reflect.klass, joins, [])
end
end
private
def inverse_association_joins(reflect)
[reflect.options[:inverse_of] || reflect.active_record.table_name]
end
end
|
khiav223577/rails_compatibility
|
test/unscope_where_test.rb
|
<filename>test/unscope_where_test.rb
require 'test_helper'
require 'rails_compatibility/unscope_where'
class UnscopeWhereTest < Minitest::Test
def setup
@females = User.where(gender: 'female')
@males = User.where(gender: 'male')
end
def test_unscope
assert_equal 4, RailsCompatibility.unscope_where(@females).count
assert_equal 1, @males.count
assert_equal 3, @females.count
end
def test_unscope_and_where
assert_equal 1, RailsCompatibility.unscope_where(@females).where(gender: 'male').count
assert_equal 1, @males.count
assert_equal 3, @females.count
end
end
|
khiav223577/rails_compatibility
|
test/has_include_test.rb
|
<gh_stars>1-10
require 'test_helper'
require 'rails_compatibility/has_include'
class HasIncludeTest < Minitest::Test
def setup
skip if ActiveRecord::VERSION::MAJOR < 4 # Rails 3 doesn't have `has_include?` method
@posts = Post.limit(1).includes(:user)
end
def test_not_become_immutable
assert_equal true, RailsCompatibility.has_include?(@posts, :id)
assert_equal false, @posts.where!(id: nil).exists?
end
end
|
khiav223577/rails_compatibility
|
test/rails_compatibility_test.rb
|
require 'test_helper'
class RailsCompatibilityTest < Minitest::Test
def setup
end
def test_that_it_has_a_version_number
refute_nil ::RailsCompatibility::VERSION
end
end
|
khiav223577/rails_compatibility
|
test/attribute_types_test.rb
|
<reponame>khiav223577/rails_compatibility<gh_stars>1-10
require 'test_helper'
require 'rails_compatibility/attribute_types'
require 'backports/2.4.0/hash/transform_values'
class AttributeTypesTest < Minitest::Test
def setup
end
def test_user
expected_attribute_types = {
'id' => :integer,
'name' => :string,
'email' => :string,
'gender' => :string,
}
assert_equal expected_attribute_types, RailsCompatibility.attribute_types(User).transform_values(&:type)
end
end
|
khiav223577/rails_compatibility
|
test/pick_test.rb
|
<filename>test/pick_test.rb
require 'test_helper'
require 'rails_compatibility/pick'
class PickTest < Minitest::Test
def setup
@females = User.where(gender: 'female')
@males = User.where(gender: 'male')
end
def test_pick_single_column
assert_equal 'Pearl', RailsCompatibility.pick(@females.order(:id), :name)
end
def test_pick_multiple_column
assert_equal %w[Pearl female], RailsCompatibility.pick(@females.order(:id), :name, :gender)
assert_equal %w[Peter male], RailsCompatibility.pick(@males.order(:id), :name, :gender)
end
def test_pick_with_offset
assert_equal %w[Catty female], RailsCompatibility.pick(@females.offset(2).order(:id), :name, :gender)
assert_nil RailsCompatibility.pick(@females.offset(999).order(:id), :name, :gender)
end
def test_pick_with_order
assert_equal 'Catty', RailsCompatibility.pick(@females.order('name ASC'), :name)
assert_equal 'Pearl', RailsCompatibility.pick(@females.order('name DESC'), :name)
if ActiveRecord::VERSION::MAJOR >= 4 # Order with hash parameters only available in ActiveRecord >= 4.0
assert_equal 'Catty', RailsCompatibility.pick(@females.order(name: :asc), :name)
assert_equal 'Pearl', RailsCompatibility.pick(@females.order(name: :desc), :name)
end
end
def test_pick_none
skip if ActiveRecord::VERSION::MAJOR < 4 # Rails 3 doesn't support none
assert_nil RailsCompatibility.pick(@females.none, :name)
end
def test_pick_no_data
assert_nil RailsCompatibility.pick(@females.where('1=0'), :name)
end
end
|
khiav223577/rails_compatibility
|
lib/rails_compatibility/pick.rb
|
# frozen_string_literal: true
require 'rails_compatibility/active_record'
class << RailsCompatibility
if GTE_RAILS_6_0
def pick(relation, *args)
relation.pick(*args)
end
elsif GTE_RAILS_4_0
def pick(relation, *args)
relation.limit(1).pluck(*args).first
end
else
def pick(relation, *args)
model = relation.first
return nil if model == nil
return model[args.first] if args.size == 1
return args.map{|s| model[s] }
end
end
end
|
scibettas1/eclectictech
|
vendor/heroku/heroku-buildpack-php/test/spec/composer_spec.rb
|
<gh_stars>1-10
require_relative "spec_helper"
describe "A PHP application" do
context "with a composer.lock generatead by an old version of Composer" do
it "builds using Composer 1.x" do
new_app_with_stack_and_platrepo('test/fixtures/composer/basic_lock_oldv1').deploy do |app|
expect(app.output).to match(/- composer \(1/)
expect(app.output).to match(/Composer version 1/)
end
end
end
context "with a composer.lock generatead by a late version 1 of Composer" do
it "builds using Composer 1.x" do
new_app_with_stack_and_platrepo('test/fixtures/composer/basic_lock_v1').deploy do |app|
expect(app.output).to match(/- composer \(1/)
expect(app.output).to match(/Composer version 1/)
end
end
end
context "with a composer.lock generatead by version 2 of Composer" do
it "builds using Composer 2.x" do
new_app_with_stack_and_platrepo('test/fixtures/composer/basic_lock_v2').deploy do |app|
expect(app.output).to match(/- composer \(2/)
expect(app.output).to match(/Composer version 2/)
end
end
end
context "with a malformed COMPOSER_AUTH env var" do
it "the app still boots" do
['v1', 'v2'].each do |cv|
new_app_with_stack_and_platrepo("test/fixtures/composer/basic_lock_#{cv}", run_multi: true).deploy do |app|
['heroku-php-apache2', 'heroku-php-nginx'].each do |script|
out = app.run("#{script} -F composer.lock", :heroku => {:env => "COMPOSER_AUTH=malformed"}) # prevent FPM from starting up using an invalid config, that way we don't have to wrap the server start in a `timeout` call
expect(out).to match(/Starting php-fpm/) # we got far enough (until FPM spits out an error)
end
end
end
end
end
end
|
ma2shita/chiliflake
|
spec/chiliflake_spec.rb
|
<filename>spec/chiliflake_spec.rb
require "chiliflake"
describe ChiliFlake, "#chiliflake" do
describe "fixed params" do
it "all zero" do
c = ChiliFlake.new(0).send(:chiliflake, ChiliFlake::OFFSET_TS_W_MILLIS, 0, 0)
expect(c).to eq 0
end
it "overflow" do
c = ChiliFlake.new(0)
expect{ c.send(:chiliflake, 2199023255552, 0, 0) }.to raise_error ChiliFlake::OverflowError
expect{ c.send(:chiliflake, ChiliFlake::OFFSET_TS_W_MILLIS, 1024, 0) }.to raise_error ChiliFlake::OverflowError
expect(c.send(:chiliflake, ChiliFlake::OFFSET_TS_W_MILLIS, 0, 4096)).to eq 0 # seq is cycliced.
end
end
describe "#new" do
it "overflow when instance create" do
expect{ ChiliFlake.new(1024) }.to raise_error ChiliFlake::OverflowError
end
end
describe "#generate" do
it "Last timestamp was bigger than now" do
c = ChiliFlake.new(0)
c.instance_variable_set(:@last_ts, (1 << ChiliFlake::TS_WIDTH) ) # tweak to the previous timestamp
expect{ c.generate }.to raise_error ChiliFlake::InvalidSystemClockError
end
end
describe "Class methods" do
it "#parse" do
h = ChiliFlake.parse(521994635925667840)
expect(h).to include(:sequence => 0)
expect(h).to include(:generator_id => 36)
expect(h).to include(:ts_w_millis => 124453219396)
end
it "#time" do
t = ChiliFlake.time(521994635925667840)
expect(t.year).to eq 2014
expect(t.month).to eq 10
expect(t.day).to eq 14
expect(t.hour).to eq 21
expect(t.min).to eq 3
expect(t.sec).to eq 14
expect(t.usec).to eq 52999
end
end
it "access to @seq" do
c = ChiliFlake.new(0)
expect(c.seq).to eq 0
c.generate
expect(c.seq).to eq 1
end
end
|
ma2shita/chiliflake
|
lib/chiliflake.rb
|
=begin
Pure ruby independent ID generator like the SnowFlake
@see https://github.com/ma2shita/chiliflake
@see https://github.com/twitter/snowflake
@author <NAME>
@example Genenate ID
generator_id = 1
i = ChiliFlake.new(generator_id)
i.generate
=> 522167874144443932
@example Parse for the Flaked ID
ChiliFlake.parse(522167874144443932)
=> {:sequence=>3612, :generator_id=>1, :ts_w_millis=>124494522606}
@example Get time in the Flaked ID
ChiliFlake.parse(522167874144443932)
=> 2014-10-15 08:31:37 +0900
=end
class ChiliFlake
attr_reader :seq
# Offset value of the timestamp computation caluculation
OFFSET_TS_W_MILLIS = 1288834974657
# structure
TS_WIDTH = 41
GEN_ID_WIDTH = 10
SEQ_WIDTH = 12
# @param [Integer] generator_id e.g.) 0 ~ 1023
def initialize(generator_id, init_seq = 0)
@last_ts = now_w_millis
@generator_id = generator_id
@seq = init_seq
chiliflake @last_ts, @generator_id, @seq # run once for parameter check
end
# Generate to the Flake ID
# @return [Integer] e.g.) 522167874144443932
# @raise [InvalidSystemClockError] If the system clock has drifted in the past then is a possibility of generate duplicate ID.
def generate
ts = now_w_millis
raise InvalidSystemClockError, "Last timestamp was bigger than now" if ts < @last_ts
@last_ts = ts
@seq = (@seq + 1) % (1 << SEQ_WIDTH) # prevention of overflow
chiliflake ts, @generator_id, @seq
end
# Parse for the Flaked ID
# @param [Integer] flake_id Flaked ID
# @return [Hash] e.g.) { :sequence=>0, :generator_id=>36, :ts_w_millis=>124453219396 }
# @example
# ChiliFlake.parse(521994635925667840)
def self.parse(flake_id)
r = {}
r[:ts_w_millis] = flake_id >> (SEQ_WIDTH + GEN_ID_WIDTH)
r[:generator_id] = (flake_id >> SEQ_WIDTH).to_s(2)[-GEN_ID_WIDTH, GEN_ID_WIDTH].to_i(2)
r[:sequence] = flake_id.to_s(2)[-SEQ_WIDTH, SEQ_WIDTH].to_i(2)
r
end
# Get time in the Flaked ID
# @param [Integer] flake_id Flaked ID
# @return [Time] e.g.) 2014-10-14 21:03:14 +0900
# @example
# ChiliFlake.time(521994635925667840)
def self.time(flake_id)
ts = (self.parse(flake_id)[:ts_w_millis] + OFFSET_TS_W_MILLIS) / 1000.0
Time.at(ts)
end
private
def chiliflake(ts_w_millis, generator_id, sequence)
raise OverflowError, "Timestamp limit is 2080-07-11 02:30:30.999 +0900" if ts_w_millis > (1 << TS_WIDTH) - 1
t = (ts_w_millis - OFFSET_TS_W_MILLIS) << (GEN_ID_WIDTH + SEQ_WIDTH)
raise OverflowError, "Generator ID limit is between 0 and 1023" if generator_id > (1 << GEN_ID_WIDTH) - 1
m = generator_id << SEQ_WIDTH
s = sequence % (1 << SEQ_WIDTH)
t + m + s
end
def now_w_millis
Time.now.strftime("%s%L").to_i
end
end
class ChiliFlake::OverflowError < StandardError ; end
class ChiliFlake::InvalidSystemClockError < StandardError ; end
|
springernature/deagol
|
lib/gollum/frontend/views/editable.rb
|
module Precious
module Editable
def formats(selected = @page.format)
Gollum::Page::FORMAT_NAMES.map do |key, val|
{ :name => val,
:id => key.to_s,
:selected => selected == key}
end.sort do |a, b|
a[:name].downcase <=> b[:name].downcase
end
end
end
end
|
springernature/deagol
|
lib/gollum/web_sequence_diagram.rb
|
require 'net/http'
require 'uri'
require 'open-uri'
class Gollum::WebSequenceDiagram
WSD_URL = "http://www.websequencediagrams.com/index.php"
# Initialize a new WebSequenceDiagram object.
#
# code - The String containing the sequence diagram markup.
# style - The String containing the rendering style.
#
# Returns a new Gollum::WebSequenceDiagram object
def initialize(code, style)
@code = code
@style = style
@tag = ""
render
end
# Render the sequence diagram on the remote server and store the url to
# the rendered image.
#
# Returns nil.
def render
response = Net::HTTP.post_form(URI.parse(WSD_URL), 'style' => @style, 'message' => @code)
if response.body =~ /img: "(.+)"/
url = "http://www.websequencediagrams.com/#{$1}"
@tag = "<img src=\"#{url}\" />"
else
puts response.body
@tag ="Sorry, unable to render sequence diagram at this time."
end
end
# Gets the HTML IMG tag for the sequence diagram.
#
# Returns a String containing the IMG tag.
def to_tag
@tag
end
end
|
springernature/deagol
|
lib/gollum/tex.rb
|
<gh_stars>100-1000
require 'fileutils'
require 'shellwords'
require 'tmpdir'
require 'posix/spawn'
module Gollum
module Tex
class Error < StandardError; end
extend POSIX::Spawn
Template = <<-EOS
\\documentclass[12pt]{article}
\\usepackage{color}
\\usepackage[dvips]{graphicx}
\\pagestyle{empty}
\\pagecolor{white}
\\begin{document}
{\\color{black}
\\begin{eqnarray*}
%s
\\end{eqnarray*}}
\\end{document}
EOS
class << self
attr_accessor :latex_path, :dvips_path, :convert_path
end
self.latex_path = 'latex'
self.dvips_path = 'dvips'
self.convert_path = 'convert'
def self.check_dependencies!
return if @dependencies_available
if `which latex` == ""
raise Error, "`latex` command not found"
end
if `which dvips` == ""
raise Error, "`dvips` command not found"
end
if `which convert` == ""
raise Error, "`convert` command not found"
end
if `which gs` == ""
raise Error, "`gs` command not found"
end
@dependencies_available = true
end
def self.render_formula(formula)
check_dependencies!
Dir.mktmpdir('tex') do |path|
tex_path = ::File.join(path, 'formula.tex')
dvi_path = ::File.join(path, 'formula.dvi')
eps_path = ::File.join(path, 'formula.eps')
png_path = ::File.join(path, 'formula.png')
::File.open(tex_path, 'w') { |f| f.write(Template % formula) }
result = sh latex_path, '-interaction=batchmode', 'formula.tex', :chdir => path
raise Error, "`latex` command failed: #{result}" unless ::File.exist?(dvi_path)
result = sh dvips_path, '-o', eps_path, '-E', dvi_path
raise Error, "`dvips` command failed: #{result}" unless ::File.exist?(eps_path)
result = sh convert_path, '+adjoin',
'-antialias',
'-transparent', 'white',
'-density', '150x150',
eps_path, png_path
raise Error, "`convert` command failed: #{result}" unless ::File.exist?(png_path)
::File.read(png_path)
end
end
private
def self.sh(*args)
pid = spawn *args
Process::waitpid(pid)
end
end
end
|
springernature/deagol
|
lib/gollum/frontend/ldap_authentication.rb
|
require 'net/ldap'
require 'yaml'
require 'digest/md5'
LDAP = YAML.load_file( File.expand_path('../../../../config/ldap.yml', __FILE__) )
module Precious
module LdapAuthentication
AUTH_TOKEN_SEED = '<PASSWORD>'
def authenticate(login, password)
authenticated_user = ldap_login(login, password)
if authenticated_user
{
:email => authenticated_user['mail'].first,
:name => authenticated_user[LDAP[:displayname_attribute]].first,
:token => Digest::MD5.hexdigest(AUTH_TOKEN_SEED + authenticated_user['mail'].first)
}
else
false
end
end
def token_ok?(email,token)
token == Digest::MD5.hexdigest(AUTH_TOKEN_SEED+email)
end
private
# Returns a single Net::LDAP::Entry or false
def ldap_login(username, password)
ldap_session = new_ldap_session
bind_args = args_for(username, password)
authenticated_user = ldap_session.bind_as(bind_args)
authenticated_user ? authenticated_user.first : false
end
# This is where LDAP jumps up and punches you in the face, all the while
# screaming "You never gunna get this, your wasting your time!".
def args_for(username, password)
user_filter = "#{ LDAP[:username_attribute] }=#{ username }"
args = { :base => LDAP[:base],
:filter => "(#{ user_filter })",
:password => password }
unless LDAP[:can_search_anonymously]
# If you can't search your LDAP directory anonymously we'll try and
# authenticate you with your user dn before we try and search for your
# account (dn example. `uid=clowder,ou=People,dc=mycompany,dc=com`).
user_dn = [user_filter, LDAP[:base]].join(',')
args.merge({ :auth => { :username => user_dn, :password => password, :method => :simple } })
end
args
end
def new_ldap_session
Net::LDAP.new(:host => LDAP[:host],
:port => LDAP[:port],
:encryption => LDAP[:encryption],
:base => LDAP[:base])
end
end
end
|
springernature/deagol
|
lib/gollum/frontend/views/login.rb
|
module Precious
module Views
class Login < Layout
def title
"Login"
end
end
end
end
|
springernature/deagol
|
lib/gollum/frontend/views/pages.rb
|
module Precious
module Views
class Pages < Layout
attr_reader :results, :ref
def title
"Browse Files"
end
def data_path
@path =~ /^\/?(.*?)\/?$/
path = $1 || ''
path << '/' unless path.empty?
" data-path=\"#{path}\""
end
def breadcrumb
breadcrumb = []
slugs = "All Files/#{@path}".split('/')
slugs.each_index do |index|
text = slugs[index]
link = ['/pages']
if index > 0
(1..index).each do |position|
link << slugs[position]
end
end
breadcrumb << "<a href=\"#{link.join('/')}/\">#{text}</a>"
end
breadcrumb.join(' / ')
end
def files_folders
files_folders = []
if has_results
@results.each do |page|
page_path = page.path.sub(/^#{@path}\//,'')
if page_path.include?('/')
folder = page_path.split('/').first
folder_path = folder
folder_path = "#{@path}/#{folder}" if @path
folder_link = "<a href=\"/pages/#{folder_path}/\" class=\"folder\">#{folder}</a>"
files_folders << folder_link if !files_folders.include?(folder_link)
else
next page if page_path == '.gitkeep'
file_path = page_path
file_path = "#{@path}/#{page_path}" if @path
files_folders << "<a href=\"/edit/#{file_path}\" class=\"file\">#{page_path}</a>"
end
end
end
files_folders.map { |f| "<li>#{f}</li>" }.join("\n")
end
def has_results
!@results.empty?
end
def no_results
@results.empty?
end
end
end
end
|
springernature/deagol
|
lib/gollum/frontend/views/history.rb
|
module Precious
module Views
class History < Layout
attr_reader :page, :page_num
def title
@page.path
end
def versions
i = @versions.size + 1
@versions.map do |v|
i -= 1
{ :id => v.id,
:id7 => v.id[0..6],
:num => i,
:selected => @page.version.id == v.id,
:author => v.author.name,
:message => v.message,
:date => v.committed_date.strftime("%B %d, %Y"),
:gravatar => Digest::MD5.hexdigest(v.author.email) }
end
end
def previous_link
label = "« Previous"
if @page_num == 1
%(<span class="disabled">#{label}</span>)
else
%(<a href="/history/#{@page.name}?page=#{@page_num-1}" hotkey="h">#{label}</a>)
end
end
def next_link
label = "Next »"
if @versions.size == Gollum::Page.per_page
%(<a href="/history/#{@page.name}?page=#{@page_num+1}" hotkey="l">#{label}</a>)
else
%(<span class="disabled">#{label}</span>)
end
end
end
end
end
|
hanachin/mruby-pkcs5
|
mrbgem.rake
|
MRuby::Gem::Specification.new('mruby-pkcs5') do |spec|
spec.license = 'MIT'
spec.author = '<NAME>'
spec.summary = 'Provide PKCS5 functionality with mruby-digest'
spec.add_dependency 'mruby-digest'
spec.add_dependency 'mruby-pack'
spec.add_dependency 'mruby-string-xor'
end
|
hanachin/mruby-pkcs5
|
mrblib/pkcs5.rb
|
module PKCS5
def self.pbkdf2_hmac(password, salt, iterations, derive_key_bytesize, digest)
hash_key_bytesize = digest.new.digest_length
derived_key = ""
n = (derive_key_bytesize / hash_key_bytesize.to_f).ceil
(1..n).each do |i|
t = u = Digest::HMAC.digest(salt + [i].pack("N"), password, digest)
(1...iterations).each do
u = Digest::HMAC.digest(u, password, digest)
t ^= u
end
derived_key += t
end
derived_key[0...derive_key_bytesize]
end
end
|
hanachin/mruby-pkcs5
|
test/mrb_pkcs5.rb
|
<gh_stars>0
# PKCS #5: Password-Based Key Derivation Function 2 (PBKDF2) Test Vectors
# https://tools.ietf.org/html/rfc6070
def dk(vector)
vector.gsub!("\n", '')
vector.gsub!(' ', '')
[vector].pack("H*")
end
assert("PKCS5.pbkdf2_hmac(password, salt, iterations, derive_key_bytesize, digest)") do
assert_equal(dk(%(
0c 60 c8 0f 96 1f 0e 71
f3 a9 b5 24 af 60 12 06
2f e0 37 a6
))) do
p = 'password'
s = '<PASSWORD>'
c = 1
dk_len = 20
PKCS5.pbkdf2_hmac(p, s, c, dk_len, Digest::SHA1)
end
assert_equal(dk(%(
ea 6c 01 4d c7 2d 6f 8c
cd 1e d9 2a ce 1d 41 f0
d8 de 89 57
))) do
p = 'password'
s = '<PASSWORD>'
c = 2
dk_len = 20
PKCS5.pbkdf2_hmac(p, s, c, dk_len, Digest::SHA1)
end
assert_equal(dk(%(
4b 00 79 01 b7 65 48 9a
be ad 49 d9 26 f7 21 d0
65 a4 29 c1
))) do
p = 'password'
s = '<PASSWORD>'
c = 4096
dk_len = 20
PKCS5.pbkdf2_hmac(p, s, c, dk_len, Digest::SHA1)
end
assert_equal(dk(%(
ee fe 3d 61 cd 4d a4 e4
e9 94 5b 3d 6b a2 15 8c
26 34 e9 84
))) do
p = 'password'
s = '<PASSWORD>'
c = 16777216
dk_len = 20
PKCS5.pbkdf2_hmac(p, s, c, dk_len, Digest::SHA1)
end
assert_equal(dk(%(
3d 2e ec 4f e4 1c 84 9b
80 c8 d8 36 62 c0 e4 4a
8b 29 1a 96 4c f2 f0 70
38
))) do
p = '<PASSWORD>password'
s = '<PASSWORD>SALTsaltSALTsaltSALTsaltSALTsalt'
c = 4096
dk_len = 25
PKCS5.pbkdf2_hmac(p, s, c, dk_len, Digest::SHA1)
end
assert_equal(dk(%(
56 fa 6a a7 55 48 09 9d
cc 37 d7 f0 34 25 e0 c3
))) do
p = "<PASSWORD>"
s = "sa\x00lt"
c = 4096
dk_len = 16
PKCS5.pbkdf2_hmac(p, s, c, dk_len, Digest::SHA1)
end
end
|
Chyrain/V5ClientWithFramework
|
V5ClientSDK.podspec
|
<reponame>Chyrain/V5ClientWithFramework
Pod::Spec.new do |s|
s.name = "V5ClientSDK"
s.version = "1.2.6"
s.summary = "A customer service SDK for users of V5KF.COM used on iOS."
s.description = <<-DESC
It is a customer service SDK used on iOS, which implement by Objective-C. More info in http://ww.v5kf.com.
DESC
s.homepage = "https://github.com/V5KF/V5KFClientSDK-iOS"
s.license = 'MIT'
s.author = { "Chyrain" => "<EMAIL>" }
s.source = { :git => "https://github.com/V5KF/V5KFClientSDK-iOS.git", :tag => "1.2.6" }
s.social_media_url = 'http://www.v5kf.com'
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'V5ClientSDK/**/*.{h,m}'
# s.ios.exclude_files = 'Classes/osx'
# s.osx.exclude_files = 'Classes/ios'
# s.public_header_files = 'Classes/**/*.h'
s.frameworks = 'Foundation', 'AVFoundation', 'CoreTelephony', 'Security', 'AudioToolbox', 'CFNetwork', 'MediaPlayer'
s.libraries = 'sqlite3', 'icucore', 'stdc++'
s.vendored_libraries = 'V5ClientSDK/**/*.a'
s.preserve_path = '**/*.a'
s.xcconfig = {"LIBRARY_SEARCH_PATHS" => "\"$(PODS_ROOT)/**\"" }
s.resources = 'V5ClientSDK/V5Client.bundle'
end
|
AssociationPaupiette/paupiette
|
app/helpers/dashboard/activity_helper.rb
|
module Dashboard::ActivityHelper
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181030150311_create_ambassadorships_join_table.rb
|
<reponame>AssociationPaupiette/paupiette
class CreateAmbassadorshipsJoinTable < ActiveRecord::Migration[5.2]
def change
create_table :ambassadorships do |t|
t.integer :user_id
t.integer :city_id
t.timestamps
end
add_index :ambassadorships, :user_id
add_index :ambassadorships, :city_id
end
end
|
AssociationPaupiette/paupiette
|
app/models/meal.rb
|
# == Schema Information
#
# Table name: meals
#
# id :bigint(8) not null, primary key
# date :datetime
# host_id :bigint(8)
# capacity :integer
# created_at :datetime not null
# updated_at :datetime not null
# confirmed :integer default(1)
# remaining :integer
# description :text
# formula :integer
#
class Meal < ApplicationRecord
enum formula: {
main: 0,
starter_main: 1,
main_dessert: 2,
starter_main_dessert: 3
}
belongs_to :host, class_name: "User"
validates_presence_of :date, :capacity, :confirmed
validates :capacity, numericality: { greater_than_or_equal_to: 1 }
validates :confirmed, numericality: { less_than_or_equal_to: :capacity, greater_than_or_equal_to: 0 }
validate :date_cannot_be_in_the_past
scope :future, -> { where('date >= ?', Date.today) }
scope :not_full, -> { where('remaining > 0') }
scope :opened, -> { future.not_full }
before_validation :denormalize_remaining
protected
def denormalize_remaining
self.remaining = self.capacity.to_i - self.confirmed.to_i
end
def date_cannot_be_in_the_past
if date.present? && date.past?
errors.add(:date, "ne peut pas être déjà passée")
end
end
end
|
AssociationPaupiette/paupiette
|
db/migrate/20181217130103_add_description_to_meal.rb
|
<gh_stars>0
class AddDescriptionToMeal < ActiveRecord::Migration[5.2]
def change
add_column :meals, :description, :text
add_column :meals, :formula, :integer
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/users_controller.rb
|
class UsersController < ApplicationController
def show
@user = User.find_by(slug: params[:user_slug])
redirect_to root_path and return if @user.nil?
if @user.latitude.present? && @user.longitude.present?
@map_center = { latitude: @user.reduced_latitude, longitude: @user.reduced_longitude }.to_json
end
@review = User::Review.new about: @user
add_breadcrumb @user
end
end
|
AssociationPaupiette/paupiette
|
app/controllers/my/profile_controller.rb
|
class My::ProfileController < My::ApplicationController
add_breadcrumb I18n.t('my.profile.name')
def index
@user = current_user
end
def update
@user = current_user
@user.assign_attributes(user_params)
if @user.valid?(:update_profile)
@user.save
redirect_to :my_profile, notice: t('my.profile.saved')
else
render :index
end
end
private
def user_params
params[:user][:reception_days] ||= []
params.require(:user).permit(:first_name, :last_name, :email, :slug, :address, :zipcode, :city_id,
:description, :photo, :specialties, :identity_card, reception_days: [])
end
end
|
AssociationPaupiette/paupiette
|
app/helpers/dashboard/open_meals_helper.rb
|
<reponame>AssociationPaupiette/paupiette<filename>app/helpers/dashboard/open_meals_helper.rb<gh_stars>0
module Dashboard::OpenMealsHelper
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.