repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
brdebr/AttndCtrl
|
spec/features/admin_authentication_spec.rb
|
require "rails_helper"
require 'ffaker'
RSpec.describe "Admin authentication" do
before(:each) do
@pass = FF<PASSWORD>::Internet.password
@admin = create :admin, password:@<PASSWORD>, password_confirmation:@pass
p 'Admin Email : ' + @admin.email
p 'Admin Password : ' + @admin.password
end
it ".log in" do
visit "/"
within '.form-inline' do
click_link 'Log in'
end
expect(page).to have_text"Email"
fill_in 'Email', with:@admin.email
fill_in 'Password', with:@admin.password
within '#new_admin' do
click_on 'Log in'
end
expect(page).to have_text @admin.email
end
end
|
brdebr/AttndCtrl
|
app/controllers/lti_users_controller.rb
|
class LtiUsersController < ApplicationController
before_action :set_lti_user, only: [:show, :edit, :update, :destroy]
# GET /lti_users
# GET /lti_users.json
def index
@lti_users = LtiUser.all
end
# GET /lti_users/1
# GET /lti_users/1.json
def show
end
# GET /lti_users/new
def new
@lti_user = LtiUser.new
end
# GET /lti_users/1/edit
def edit
end
# POST /lti_users
# POST /lti_users.json
def create
@lti_user = LtiUser.new(lti_user_params)
respond_to do |format|
if @lti_user.save
format.html { redirect_to @lti_user, notice: 'Lti user was successfully created.' }
format.json { render :show, status: :created, location: @lti_user }
else
format.html { render :new }
format.json { render json: @lti_user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /lti_users/1
# PATCH/PUT /lti_users/1.json
def update
respond_to do |format|
if @lti_user.update(lti_user_params)
format.html { redirect_to @lti_user, notice: 'Lti user was successfully updated.' }
format.json { render :show, status: :ok, location: @lti_user }
else
format.html { render :edit }
format.json { render json: @lti_user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /lti_users/1
# DELETE /lti_users/1.json
def destroy
@lti_user.destroy
respond_to do |format|
format.html { redirect_to lti_users_url, notice: 'Lti user was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_lti_user
@lti_user = LtiUser.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def lti_user_params
params.require(:lti_user).permit(:full_name, :given, :family, :username, :email)
end
end
|
brdebr/AttndCtrl
|
app/models/lti_user.rb
|
<gh_stars>0
class LtiUser < ApplicationRecord
belongs_to :lti_role
end
|
brdebr/AttndCtrl
|
db/migrate/20180607195057_add_lti_id_to_lti_user.rb
|
<filename>db/migrate/20180607195057_add_lti_id_to_lti_user.rb
class AddLtiIdToLtiUser < ActiveRecord::Migration[5.1]
def change
add_column :lti_users, :lti_id, :integer
end
end
|
brdebr/AttndCtrl
|
app/models/tool_consumer.rb
|
<reponame>brdebr/AttndCtrl
class ToolConsumer < ApplicationRecord
belongs_to :admin
has_many :timetables, dependent: :delete_all
accepts_nested_attributes_for :timetables, allow_destroy: true, reject_if: lambda { |attr| attr['name'].blank?}
end
|
brdebr/AttndCtrl
|
test/system/tool_consumers_test.rb
|
require "application_system_test_case"
class ToolConsumersTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit tool_consumers_url
#
# assert_selector "h1", text: "ToolConsumer"
# end
end
|
brdebr/AttndCtrl
|
config/environment.rb
|
# Load the Rails application.
require_relative 'application'
OAUTH_10_SUPPORT = true
# Initialize the Rails application.
Rails.application.initialize!
|
brdebr/AttndCtrl
|
spec/controllers/timetable_units_controller_spec.rb
|
<filename>spec/controllers/timetable_units_controller_spec.rb
require 'rails_helper'
RSpec.describe TimetableUnitsController, type: :controller do
end
|
brdebr/AttndCtrl
|
app/models/lti_role.rb
|
class LtiRole < ApplicationRecord
has_many :lti_users
end
|
brdebr/AttndCtrl
|
config/routes.rb
|
Rails.application.routes.draw do
resources :lti_contexts
resources :lti_users
devise_for :admins
root 'home#main'
# Admins need to create a ToolConsumer object to authenticate the launch with the generated key/secret
resources :tool_consumers do
resources :timetables, controller: 'tool_consumers/timetables', shallow: true
end
resources :timetable, only: :show do
resources :timetable_units, shallow: true
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get 'dashboard', to: "home#dashboard"
# LTI launch (responds to get and post)
match 'launch', to: "lti#launch", via: [:get, :post], as: :lti_launch
end
|
brdebr/AttndCtrl
|
app/views/tool_consumers/show.json.jbuilder
|
<reponame>brdebr/AttndCtrl
json.partial! "tool_consumers/tool_consumer", tool_consumer: @tool_consumer
|
brdebr/AttndCtrl
|
spec/factories/timetable_units.rb
|
<filename>spec/factories/timetable_units.rb
FactoryBot.define do
factory :timetable_unit do
name "MyString"
description "MyText"
week_day 1
start_time "2018-06-03 23:04:57"
finish_time "2018-06-03 23:04:57"
end
end
|
brdebr/AttndCtrl
|
spec/factories/lti_users.rb
|
<filename>spec/factories/lti_users.rb
FactoryBot.define do
factory :lti_user do
full_name "MyString"
given "MyString"
family "MyString"
username "MyString"
email "MyString"
end
end
|
brdebr/AttndCtrl
|
db/migrate/20180603210457_create_timetable_units.rb
|
<reponame>brdebr/AttndCtrl
class CreateTimetableUnits < ActiveRecord::Migration[5.1]
def change
create_table :timetable_units do |t|
t.string :name
t.text :description
t.integer :week_day
t.time :start_time
t.time :finish_time
t.timestamps
end
end
end
|
brdebr/AttndCtrl
|
db/migrate/20180608013852_add_lti_role_to_lti_user.rb
|
class AddLtiRoleToLtiUser < ActiveRecord::Migration[5.1]
def change
add_reference :lti_users, :lti_role, foreign_key: true
end
end
|
brdebr/AttndCtrl
|
spec/factories/tool_consumer_factory.rb
|
require 'ffaker'
FactoryBot.define do
factory :tool_consumer do
name { FFaker::Education.school }
key { FFaker::Education.school_name }
secret { FFaker::Internet.password }
end
end
|
brdebr/AttndCtrl
|
app/views/tool_consumers/timetables/_timetable.json.jbuilder
|
<filename>app/views/tool_consumers/timetables/_timetable.json.jbuilder
json.extract! timetable, :id, :name, :created_at, :updated_at
json.url timetable_url(timetable, format: :json)
|
brdebr/AttndCtrl
|
spec/features/guest_authentication_spec.rb
|
require 'rails_helper'
require 'ffaker'
RSpec.describe 'Guest signs up' do
before(:each) do
@pass = <PASSWORD>
@guest = build :admin, password:@<PASSWORD>, password_confirmation:@pass
p 'Guest Email : ' + @guest.email
p 'Guest Password : ' + @guest.password
end
it '.visits the homepage' do
visit "/"
expect(page).to have_text"This is the public page"
end
it ".visits dashboard by url and fails" do
visit "/dashboard"
expect(page).to have_text"Error"
end
it ".visits lti launch and fails" do
visit "/launch"
expect(page).to have_text"Authentication error"
end
it '.becomes admin' do
visit "/"
within '.form-inline' do
click_link 'Log in'
end
click_link 'Sign up'
fill_in 'Email', with:@guest.email
fill_in 'Password', with:<PASSWORD>
fill_in 'Password confirmation', with:<PASSWORD>.password
click_button 'Sign up'
expect(page).to have_text @guest.email
expect(page).to have_text 'Welcome'
expect(page).to have_text 'Dashboard'
# Use for debugging
# save_and_open_page
end
end
|
brdebr/AttndCtrl
|
app/views/tool_consumers/index.json.jbuilder
|
json.array! @tool_consumers, partial: 'tool_consumers/tool_consumer', as: :tool_consumer
|
brdebr/AttndCtrl
|
app/controllers/tool_consumers/timetables_controller.rb
|
<filename>app/controllers/tool_consumers/timetables_controller.rb
class ToolConsumers::TimetablesController < ApplicationController
before_action :authenticate_admin!, except: :show
before_action :set_timetable, only: [:show, :edit, :update, :destroy]
before_action :set_tool_consumer, except: [:new, :create]
# GET /timetables
# GET /timetables.json
def index
@timetables = Timetable.all
end
# GET /timetables/1
# GET /timetables/1.json
def show
@new_timetable_u = TimetableUnit.new
@new_timetable_u.timetable = @timetable
gon.clear
if TimetableUnit.find_by(timetable_id:@timetable).nil?
@timetable_u = TimetableUnit.new
else
@timetable_u = TimetableUnit.find_by timetable_id:@timetable.id
@new_timetable_u = TimetableUnit.new
gon.timetable_u = @timetable_u
end
gon.timetable_id = @timetable.id
end
# GET /timetables/new
def new
@timetable = Timetable.new
@tool_consumer = ToolConsumer.find_by id:params['tool_consumer_id'], admin:current_admin
if @tool_consumer.nil?
render file: 'public/404', status: :not_found
end
end
# GET /timetables/1/edit
def edit
end
# POST /timetables
# POST /timetables.json
def create
@timetable = Timetable.new(timetable_params)
@timetable.tool_consumer = ToolConsumer.find_by id:params['tool_consumer_id'], admin:current_admin
if @timetable.tool_consumer.nil?
render file: 'public/404', status: :not_found
end
respond_to do |format|
if @timetable.save
format.html { redirect_to @timetable.tool_consumer, notice: 'Timetable was successfully created.' }
format.json { render :show, status: :created, location: @timetable }
else
format.html { render :new }
format.json { render json: @timetable.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /timetables/1
# PATCH/PUT /timetables/1.json
def update
respond_to do |format|
if @timetable.update(timetable_params)
format.html { redirect_to @timetable, notice: 'Timetable was successfully updated.' }
format.json { render :show, status: :ok, location: @timetable }
else
format.html { render :edit }
format.json { render json: @timetable.errors, status: :unprocessable_entity }
end
end
end
# DELETE /timetables/1
# DELETE /timetables/1.json
def destroy
@timetable.destroy
respond_to do |format|
format.html { redirect_to @tool_consumer, notice: 'Timetable was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_timetable
@timetable = Timetable.find(params[:id])
end
def set_tool_consumer
@tool_consumer = ToolConsumer.find_by id:@timetable.tool_consumer.id, admin:current_admin
if @tool_consumer.nil?
render file: 'public/404', status: :not_found
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def timetable_params
params.require(:timetable).permit(:name)
end
end
|
brdebr/AttndCtrl
|
spec/features/tool_consumers_timetables_spec.rb
|
<reponame>brdebr/AttndCtrl<gh_stars>0
require "rails_helper"
require 'ffaker'
RSpec.describe "Tool consumers management" do
before(:each) do
@pass = <PASSWORD>::Internet.password
@admin = create :admin, password:@<PASSWORD>, password_confirmation:@pass
p 'Admin - Email : ' + @admin.email
p 'Admin - Password : ' + @admin.password
@tool_consumer_b = build :tool_consumer
p 'Tool Consumer - Name : ' + @tool_consumer_b.name
p 'Tool Consumer - Key : ' + @tool_consumer_b.key
p 'Tool Consumer - Secret : ' + @tool_consumer_b.secret
end
it ".log in" do
visit "/"
within '.form-inline' do
click_link 'Log in'
end
expect(page).to have_text"Email"
fill_in 'Email', with:@admin.email
fill_in 'Password', with:<PASSWORD>
within '#new_admin' do
click_on 'Log in'
end
expect(page).to have_text @admin.email
end
it '.create Tool Consumer' do
# ---------------vv------------vv---------------
visit "/"
within '.form-inline' do
click_link 'Log in'
end
expect(page).to have_text"Email"
fill_in 'Email', with:@admin.email
fill_in 'Password', with:<PASSWORD>
within '#new_admin' do
click_on 'Log in'
end
expect(page).to have_text @admin.email
# -------- TODO refactor ^^ this ^^ , duplicated
click_on 'Tool consumers'
expect(page).to have_text"No Tool Consumers to show"
click_link 'New Tool Consumer'
# save_and_open_page
fill_in 'Name', with:@tool_consumer_b.name
fill_in 'Key', with:@tool_consumer_b.key
fill_in 'Secret', with:@tool_consumer_b.secret
click_on 'Create Tool consumer'
expect(page).to have_text"successfully"
expect(page).to have_text @tool_consumer_b.name
expect(page).to have_text @tool_consumer_b.key
expect(page).to have_text @tool_consumer_b.secret
click_link 'Back'
expect(page).to have_text @tool_consumer_b.name
end
end
|
brdebr/AttndCtrl
|
app/models/timetable.rb
|
class Timetable < ApplicationRecord
belongs_to :tool_consumer
has_many :timetable_units
accepts_nested_attributes_for :timetable_units, allow_destroy: true, reject_if: lambda { |attr| attr['name'].blank?}
end
|
brdebr/AttndCtrl
|
test/system/lti_contexts_test.rb
|
require "application_system_test_case"
class LtiContextsTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit lti_contexts_url
#
# assert_selector "h1", text: "LtiContext"
# end
end
|
brdebr/AttndCtrl
|
app/controllers/tool_consumers_controller.rb
|
class ToolConsumersController < ApplicationController
before_action :authenticate_admin!
before_action :set_tool_consumer, only: [:show, :edit, :update, :destroy]
# GET /tool_consumers
# GET /tool_consumers.json
def index
@tool_consumers = ToolConsumer.where admin:current_admin
end
# GET /tool_consumers/1
# GET /tool_consumers/1.json
def show
end
# GET /tool_consumers/new
def new
@tool_consumer = ToolConsumer.new
@tool_consumer.secret = SecureRandom.base64(12)
end
# GET /tool_consumers/1/edit
def edit
end
# POST /tool_consumers
# POST /tool_consumers.json
def create
@tool_consumer = ToolConsumer.new(tool_consumer_params)
@tool_consumer.admin = current_admin
respond_to do |format|
if @tool_consumer.save
format.html { redirect_to @tool_consumer, notice: 'Tool consumer was successfully created.' }
format.json { render :show, status: :created, location: @tool_consumer }
else
format.html { render :new }
format.json { render json: @tool_consumer.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tool_consumers/1
# PATCH/PUT /tool_consumers/1.json
def update
respond_to do |format|
if @tool_consumer.update(tool_consumer_params)
format.html { redirect_to @tool_consumer, notice: 'Tool consumer was successfully updated.' }
format.json { render :show, status: :ok, location: @tool_consumer }
else
format.html { render :edit }
format.json { render json: @tool_consumer.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tool_consumers/1
# DELETE /tool_consumers/1.json
def destroy
@tool_consumer.destroy
respond_to do |format|
format.html { redirect_to tool_consumers_url, notice: 'Tool consumer was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tool_consumer
@tool_consumer = ToolConsumer.find_by id:params[:id], admin:current_admin
# TODO refactor this to a Concern, it will be used a lot
if @tool_consumer.nil?
render file: 'public/404', status: :not_found
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def tool_consumer_params
params.require(:tool_consumer).permit(:name, :key, :secret, timetable_attributes: [:tool_consumer_id,:name])
end
end
|
brdebr/AttndCtrl
|
app/controllers/home_controller.rb
|
<reponame>brdebr/AttndCtrl
class HomeController < ApplicationController
before_action :authenticate_admin!, except: [:main]
def main
end
def dashboard
end
def test_oauth
end
end
|
brdebr/AttndCtrl
|
test/controllers/timetables_controller_test.rb
|
require 'test_helper'
class TimetablesControllerTest < ActionDispatch::IntegrationTest
setup do
@timetable = timetables(:one)
end
test "should get index" do
get timetables_url
assert_response :success
end
test "should get new" do
get new_timetable_url
assert_response :success
end
test "should create timetable" do
assert_difference('Timetable.count') do
post timetables_url, params: { timetable: { name: @timetable.name } }
end
assert_redirected_to timetable_url(Timetable.last)
end
test "should show timetable" do
get timetable_url(@timetable)
assert_response :success
end
test "should get edit" do
get edit_timetable_url(@timetable)
assert_response :success
end
test "should update timetable" do
patch timetable_url(@timetable), params: { timetable: { name: @timetable.name } }
assert_redirected_to timetable_url(@timetable)
end
test "should destroy timetable" do
assert_difference('Timetable.count', -1) do
delete timetable_url(@timetable)
end
assert_redirected_to timetables_url
end
end
|
brdebr/AttndCtrl
|
app/helpers/application_helper.rb
|
module ApplicationHelper
def current_active_page?(test_path)
return 'active' if request.path == test_path
''
end
end
|
brdebr/AttndCtrl
|
app/views/lti_users/_lti_user.json.jbuilder
|
json.extract! lti_user, :id, :full_name, :given, :family, :username, :email, :created_at, :updated_at
json.url lti_user_url(lti_user, format: :json)
|
brdebr/AttndCtrl
|
test/system/lti_users_test.rb
|
require "application_system_test_case"
class LtiUsersTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit lti_users_url
#
# assert_selector "h1", text: "LtiUser"
# end
end
|
brdebr/AttndCtrl
|
app/views/lti_users/show.json.jbuilder
|
<gh_stars>0
json.partial! "lti_users/lti_user", lti_user: @lti_user
|
brdebr/AttndCtrl
|
app/controllers/timetable_units_controller.rb
|
class TimetableUnitsController < ApplicationController
before_action :authenticate_admin!, except: :index
# GET /timetable_us
# GET /timetable_us.json
def index
@timetable_u = TimetableUnit.where timetable_id:params['timetable_id']
respond_to do |format|
format.html
format.json { render :json => @timetable_u }
end
end
# GET /timetable_us/1
# GET /timetable_us/1.json
def show
end
# GET /timetable_us/new
def new
@timetable_u = TimetableUnit.new
end
# GET /timetable_us/1/edit
def edit
end
# POST /timetable_us
# POST /timetable_us.json
def create
@timetable_u = TimetableUnit.new(timetable_u_params) ##
@timetable_u.timetable = Timetable.find params['timetable_id']
p @timetable
respond_to do |format|
if @timetable_u.save
format.html { redirect_to timetable_url id:@timetable_u.timetable}
format.json { render :show, status: :created, location: @timetable_u }
else
format.json { render json: @timetable_u.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /timetable_us/1
# PATCH/PUT /timetable_us/1.json
def update
respond_to do |format|
if @timetable_u.update(timetable_u_params)
format.json { render :show, status: :ok, location: @timetable_u }
else
format.json { render json: @timetable_u.errors, status: :unprocessable_entity }
end
end
end
# DELETE /timetable_us/1
# DELETE /timetable_us/1.json
def destroy
@timetable_u.destroy
respond_to do |format|
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_timetable_u
@timetable_u = TimetableUnit.find params[:id]
end
def set_timetable
@timetable = Timetable.find params[:timetable_id]
end
def set_tool_consumer
@tool_consumer = ToolConsumer.find_by id:@timetable_u.tool_consumer.id, admin:current_admin
if @tool_consumer.nil?
render file: 'public/404', status: :not_found
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def timetable_u_params
params.require(:timetable_unit).permit(:name,:start_time, :finish_time, :description,:week_day)
end
end
|
brdebr/AttndCtrl
|
app/views/lti_users/index.json.jbuilder
|
<gh_stars>0
json.array! @lti_users, partial: 'lti_users/lti_user', as: :lti_user
|
brdebr/AttndCtrl
|
app/models/timetable_unit.rb
|
class TimetableUnit < ApplicationRecord
belongs_to :timetable
def as_json(options = {})
{
:id => self.id,
:title => "· "+self.name.capitalize.truncate(15)+"\n"+self.description.truncate(30),
:start => self.start_time.strftime("%H:%M"),
:end => self.finish_time.strftime("%H:%M"),
:dow => [self.week_day],
:url => Rails.application.routes.url_helpers.timetable_path(self.timetable),
:color => "#"+SecureRandom.hex(3).to_s
}
end
end
|
brdebr/AttndCtrl
|
spec/factories/lti_contexts.rb
|
FactoryBot.define do
factory :lti_context do
lti_id 1
label "MyString"
title "MyString"
end
end
|
brdebr/AttndCtrl
|
app/models/lti_context.rb
|
<filename>app/models/lti_context.rb
class LtiContext < ApplicationRecord
end
|
brdebr/AttndCtrl
|
test/controllers/tool_consumers_controller_test.rb
|
require 'test_helper'
class ToolConsumersControllerTest < ActionDispatch::IntegrationTest
setup do
@tool_consumer = tool_consumers(:one)
end
test "should get index" do
get tool_consumers_url
assert_response :success
end
test "should get new" do
get new_tool_consumer_url
assert_response :success
end
test "should create tool_consumer" do
assert_difference('ToolConsumer.count') do
post tool_consumers_url, params: { tool_consumer: { key: @tool_consumer.key, name: @tool_consumer.name, secret: @tool_consumer.secret } }
end
assert_redirected_to tool_consumer_url(ToolConsumer.last)
end
test "should show tool_consumer" do
get tool_consumer_url(@tool_consumer)
assert_response :success
end
test "should get edit" do
get edit_tool_consumer_url(@tool_consumer)
assert_response :success
end
test "should update tool_consumer" do
patch tool_consumer_url(@tool_consumer), params: { tool_consumer: { key: @tool_consumer.key, name: @tool_consumer.name, secret: @tool_consumer.secret } }
assert_redirected_to tool_consumer_url(@tool_consumer)
end
test "should destroy tool_consumer" do
assert_difference('ToolConsumer.count', -1) do
delete tool_consumer_url(@tool_consumer)
end
assert_redirected_to tool_consumers_url
end
end
|
brdebr/AttndCtrl
|
app/controllers/lti_controller.rb
|
<filename>app/controllers/lti_controller.rb<gh_stars>0
class LtiController < ApplicationController
include LtiAuthLaunchConcern
skip_before_action :verify_authenticity_token
def launch
render :launch_error, status: 401 unless is_oauth_valid?
end
end
|
brdebr/AttndCtrl
|
app/views/lti_contexts/index.json.jbuilder
|
json.array! @lti_contexts, partial: 'lti_contexts/lti_context', as: :lti_context
|
brdebr/AttndCtrl
|
app/views/lti_contexts/show.json.jbuilder
|
<reponame>brdebr/AttndCtrl<filename>app/views/lti_contexts/show.json.jbuilder
json.partial! "lti_contexts/lti_context", lti_context: @lti_context
|
brdebr/AttndCtrl
|
app/views/lti_contexts/_lti_context.json.jbuilder
|
json.extract! lti_context, :id, :lti_id, :label, :title, :created_at, :updated_at
json.url lti_context_url(lti_context, format: :json)
|
brdebr/AttndCtrl
|
db/migrate/20180527111236_add_admin_to_tool_consumer.rb
|
<filename>db/migrate/20180527111236_add_admin_to_tool_consumer.rb
class AddAdminToToolConsumer < ActiveRecord::Migration[5.1]
def change
add_reference :tool_consumers, :admin, foreign_key: true
end
end
|
brdebr/AttndCtrl
|
app/controllers/concerns/lti_auth_launch_concern.rb
|
# Required for LTI
require 'ims/lti'
# Used to validate oauth signatures
require 'oauth/request_proxy/action_controller_request'
module LtiAuthLaunchConcern
extend ActiveSupport::Concern
def is_oauth_valid?
# Search for a ToolConsumer with the param 'key' equal to :
# the result of getting the 'parameters' array from inside the 'request' object.
# The 'request' object is provided by Ruby on Rails and has many data about the request received from the user browser
tc = ToolConsumer.find_by key:request.parameters['oauth_consumer_key']
if tc.present?
authenticator = IMS::LTI::Services::MessageAuthenticator.new(request.url, request.request_parameters, tc.secret)
else
return false
end
# Check if the signature is valid
if !authenticator.valid_signature?
return false
end
# Check if the request timestamp was 5 minutes ago
if DateTime.strptime(request.request_parameters['oauth_timestamp'],'%s') < 5.minutes.ago
return false
end
# The provider request is valid
# store the values you need from the LTI
# here we're just tossing them into the session
@lti_user = LtiUser.find_by lti_id:params.require(:user_id)
if @lti_user.nil?
@lti_user = LtiUser.create lti_id: params.require(:user_id),
full_name: params.require(:lis_person_name_full),
given: params['lis_person_name_given'],
family: params['lis_person_name_family'],
username: params['ext_user_username'],
email: params['lis_person_contact_email_primary']
end
@lti_context = LtiContext.find_or_create_by lti_id:params.require(:context_id)
if params['roles'].include? 'Instructor'
@lti_role = LtiRole.find_or_create_by name:'Instructor'
elsif params['roles'].include? 'Learner'
@lti_role = LtiRole.find_or_create_by name:'Learner'
end
@lti_user = @lti_user.first if @lti_user.class == Array
@lti_user.update lti_role:@lti_role
if @lti_context
@lti_context = LtiContext.update label:params['context_label'],
title:params['context_title']
end
@tool_consumer = tc
return true
end
end
|
brdebr/AttndCtrl
|
app/controllers/lti_contexts_controller.rb
|
<gh_stars>0
class LtiContextsController < ApplicationController
before_action :set_lti_context, only: [:show, :edit, :update, :destroy]
# GET /lti_contexts
# GET /lti_contexts.json
def index
@lti_contexts = LtiContext.all
end
# GET /lti_contexts/1
# GET /lti_contexts/1.json
def show
end
# GET /lti_contexts/new
def new
@lti_context = LtiContext.new
end
# GET /lti_contexts/1/edit
def edit
end
# POST /lti_contexts
# POST /lti_contexts.json
def create
@lti_context = LtiContext.new(lti_context_params)
respond_to do |format|
if @lti_context.save
format.html { redirect_to @lti_context, notice: 'Lti context was successfully created.' }
format.json { render :show, status: :created, location: @lti_context }
else
format.html { render :new }
format.json { render json: @lti_context.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /lti_contexts/1
# PATCH/PUT /lti_contexts/1.json
def update
respond_to do |format|
if @lti_context.update(lti_context_params)
format.html { redirect_to @lti_context, notice: 'Lti context was successfully updated.' }
format.json { render :show, status: :ok, location: @lti_context }
else
format.html { render :edit }
format.json { render json: @lti_context.errors, status: :unprocessable_entity }
end
end
end
# DELETE /lti_contexts/1
# DELETE /lti_contexts/1.json
def destroy
@lti_context.destroy
respond_to do |format|
format.html { redirect_to lti_contexts_url, notice: 'Lti context was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_lti_context
@lti_context = LtiContext.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def lti_context_params
params.require(:lti_context).permit(:lti_id, :label, :title)
end
end
|
brdebr/AttndCtrl
|
spec/factories/admin_factory.rb
|
<gh_stars>0
require 'ffaker'
FactoryBot.define do
factory :admin do
email { FFaker::Internet.free_email }
password "<PASSWORD>"
password_confirmation "<PASSWORD>"
end
end
|
brdebr/AttndCtrl
|
db/schema.rb
|
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20180608013852) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "admins", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_admins_on_email", unique: true
t.index ["reset_password_token"], name: "index_admins_on_reset_password_token", unique: true
end
create_table "lti_contexts", force: :cascade do |t|
t.integer "lti_id"
t.string "label"
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "lti_roles", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "lti_users", force: :cascade do |t|
t.string "full_name"
t.string "given"
t.string "family"
t.string "username"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "lti_id"
t.bigint "lti_role_id"
t.index ["lti_role_id"], name: "index_lti_users_on_lti_role_id"
end
create_table "timetable_units", force: :cascade do |t|
t.string "name"
t.text "description"
t.integer "week_day"
t.time "start_time"
t.time "finish_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "timetable_id"
t.index ["timetable_id"], name: "index_timetable_units_on_timetable_id"
end
create_table "timetables", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "tool_consumer_id"
t.index ["tool_consumer_id"], name: "index_timetables_on_tool_consumer_id"
end
create_table "tool_consumers", force: :cascade do |t|
t.string "name"
t.string "key"
t.string "secret"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "admin_id"
t.index ["admin_id"], name: "index_tool_consumers_on_admin_id"
end
add_foreign_key "lti_users", "lti_roles"
add_foreign_key "timetable_units", "timetables"
add_foreign_key "timetables", "tool_consumers"
add_foreign_key "tool_consumers", "admins"
end
|
brdebr/AttndCtrl
|
app/views/tool_consumers/_tool_consumer.json.jbuilder
|
json.extract! tool_consumer, :id, :name, :key, :secret, :created_at, :updated_at
json.url tool_consumer_url(tool_consumer, format: :json)
|
charlie22c/spree_shipstation
|
spec/spec_helper.rb
|
# Run Coverage report
require 'simplecov'
SimpleCov.start do
add_filter 'spec/dummy'
add_group 'Controllers', 'app/controllers'
add_group 'Helpers', 'app/helpers'
add_group 'Mailers', 'app/mailers'
add_group 'Models', 'app/models'
add_group 'Views', 'app/views'
add_group 'Libraries', 'lib'
end
# Configure Rails Environment
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
require 'database_cleaner'
require 'ffaker'
# Requires factories and other useful helpers defined in spree_core.
require 'spree/testing_support/authorization_helpers'
require 'spree/testing_support/capybara_ext'
require 'spree/testing_support/controller_requests'
require 'spree/testing_support/factories' # commented because error: `method_missing': Factory already registered: shipment (FactoryGirl::DuplicateDefinitionError)
require 'spree/testing_support/url_helpers'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f }
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } # didn't load anything
# Requires factories defined in lib/spree_shipstation/factories.rb
# require "spree_shipstation/factories"
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
# config.before do
# FactoryGirl.definition_file_paths = [File.expand_path('../factories', __FILE__)]
# FactoryGirl.find_definitions
# end
#
# config.before(:all) do
# FactoryGirl.reload
# end
# Infer an example group's spec type from the file location.
config.infer_spec_type_from_file_location!
# == URL Helpers
#
# Allows access to Spree's routes in specs:
#
# visit spree.admin_path
# current_path.should eql(spree.products_path)
config.include Spree::TestingSupport::UrlHelpers
# == Requests support
#
# Adds convenient methods to request Spree's controllers
# spree_get :index
config.include Spree::TestingSupport::ControllerRequests, type: :controller
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
config.color = true
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# Capybara javascript drivers require transactional fixtures set to false, and we use DatabaseCleaner
# to cleanup after each test instead. Without transactional fixtures set to false the records created
# to setup a test will be unavailable to the browser, which runs under a separate server instance.
config.use_transactional_fixtures = false
# Ensure Suite is set to use transactions for speed.
config.before :suite do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
end
# Before each spec check if it is a Javascript test and switch between using database transactions or not where necessary.
config.before :each do
DatabaseCleaner.strategy = RSpec.current_example.metadata[:js] ? :truncation : :transaction
DatabaseCleaner.start
end
# After each spec clean the database.
config.after :each do
DatabaseCleaner.clean
end
config.fail_fast = ENV['FAIL_FAST'] || false
config.order = "random"
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
|
charlie22c/spree_shipstation
|
app/views/spree/shipstation/export.xml.builder
|
<reponame>charlie22c/spree_shipstation
date_format = "%m/%d/%Y %H:%M"
def address(xml, address, type, order)
name = "#{type.to_s.titleize}To"
xml.__send__(name) {
xml.Name trim_field(address.full_name, 100)
xml.Company trim_field(address.company, 100)
if type == :ship
xml.Address1 trim_field(address.address1, 200)
xml.Address2 trim_field(address.address2, 200)
xml.City trim_field(address.city, 100)
xml.State address.state ? address.state.abbr : address.state_name
xml.PostalCode address.zipcode
xml.Country address.country.iso
end
xml.Phone trim_field(address.phone, 50)
if type == :bill
xml.Email trim_field(order.email, 100)
end
}
end
def trim_field(value, length)
(value || "").slice(0, length)
end
xml.instruct!
xml.Orders(pages: ((1.0*@shipments.total_count)/@page_size).ceil) {
@shipments.each do |shipment|
order = shipment.order
xml.Order {
xml.OrderID shipment.id
xml.OrderNumber Spree::Config.shipstation_number == :order ? order.number : shipment.number
xml.OrderDate (order.completed_at || order.created_at).utc.strftime(date_format)
xml.OrderStatus shipment.state
xml.LastModified [order.completed_at, shipment.updated_at].max.utc.strftime(date_format)
xml.ShippingMethod shipment.shipping_method.try(:name)
xml.OrderTotal order.total
xml.TaxAmount order.additional_tax_total
xml.ShippingAmount order.shipment_total
if order.respond_to? :shipstation_custom_field_1
xml.CustomField1 trim_field(order.shipstation_custom_field_1, 100)
else
xml.CustomField1 order.number
end
if order.respond_to? :shipstation_custom_field_2
xml.CustomField2 trim_field(order.shipstation_custom_field_2, 100)
end
if order.respond_to? :shipstation_custom_field_3
xml.CustomField3 trim_field(order.shipstation_custom_field_3, 100)
end
if order.respond_to?(:gift?)
xml.Gift order.gift?
xml.GiftMessage trim_field(order.gift_wrapping_message, 1000)
end
unless order.special_instructions.blank?
xml.CustomerNotes trim_field(order.special_instructions, 1000)
end
xml.Customer {
xml.CustomerCode trim_field(order.email, 50)
address(xml, order.bill_address, :bill, order)
if shipment.respond_to?(:alternate_ship_address) && shipment.alternate_ship_address
address(xml, shipment.alternate_ship_address, :ship, order)
else
address(xml, order.ship_address, :ship, order)
end
}
xml.Items {
shipment.variants_hash_for_export.each_pair do |variant, quantity_and_price|
xml.Item {
xml.SKU variant.sku
xml.Name trim_field([variant.product.name, variant.options_text].join(' '), 200)
xml.ImageUrl variant.images.first.try(:attachment).try(:url)
xml.Weight variant.weight.to_f
xml.WeightUnits Spree::Config.shipstation_weight_units
xml.Quantity quantity_and_price[:quantity]
xml.UnitPrice quantity_and_price[:price].round(2)
xml.Location variant.try(:stock_items).first.try(:shelf_location) || ""
if variant.option_values.present?
xml.Options {
variant.option_values.each do |value|
xml.Option {
xml.Name value.option_type.presentation
xml.Value value.option_type.presentation == "Color" ? value.presentation : value.name
}
end
}
end
}
end
if order.respond_to?(:shipstation_bonus_items)
order.shipstation_bonus_items(shipment).each do |item|
xml.Item {
xml.SKU item[:sku]
xml.Name trim_field(item[:name], 200)
xml.ImageUrl item[:image_url]
xml.Weight item[:weight]
xml.WeightUnits Spree::Config.shipstation_weight_units
xml.Quantity item[:quantity]
xml.UnitPrice item[:price].round(2)
xml.Location item[:location] || ''
}
end
end
}
}
end
}
|
charlie22c/spree_shipstation
|
app/models/spree/shipment_decorator.rb
|
Spree::Shipment.class_eval do
scope :exportable, -> {
joins(:order)
.where('spree_shipments.state != ?', 'pending')
.where("#{Spree::Order.table_name}.completed_at > ?", Time.new(2020, 1, 1))
}
def self.between(from, to)
joins(:order).where('spree_orders.updated_at between ? AND ?', from, to)
end
def variants_hash_for_export
# call product assembly method, then combine each variant since Shipstation wants
# each sku to appear only once
line_items.each_with_object({}) do |line, memo|
if line.product.assembly?
if line.part_line_items.any?
line.part_line_items.each do |pli|
add_to_memo(memo, pli.variant, pli.proportional_unit_price, pli.quantity * line.quantity)
end
else
line.variant.parts_variants.each do |pv|
add_to_memo(memo, pv.part, pv.proportional_unit_price, pv.count)
end
end
else
add_to_memo(memo, line.variant, line.price, line.quantity)
end
end
end
def add_to_memo(memo, variant, price, quantity)
if quantity > 0
memo[variant] ||= { price: 0, quantity: 0 }
memo[variant][:price] = (memo[variant][:price]*memo[variant][:quantity] + quantity * price) / (memo[variant][:quantity] + quantity)
memo[variant][:quantity] += quantity
end
end
end
|
charlie22c/spree_shipstation
|
lib/spree_shipstation.rb
|
require 'spree_core'
require 'spree_shipstation/engine'
require 'spree/shipment_notice'
module Spree
extend ActionView::Helpers::TagHelper
end
|
charlie22c/spree_shipstation
|
app/models/spree/shipment_handler_decorator.rb
|
Spree::ShipmentHandler.class_eval do
private
def send_shipped_email
Spree::ShipmentMailer.shipped_email(@shipment.id).deliver_later if Spree::Config.send_shipped_email
end
end
|
charlie22c/spree_shipstation
|
spec/models/spree/shipment_spec.rb
|
<gh_stars>0
require 'spec_helper'
describe Spree::Shipment do
context "between" do
before do
@active = []
@dt1 = 1.day.ago
@dt2 = 1.day.from_now
@dt_now = Time.now
Timecop.travel(@dt1) do
@shipment1 = create(:shipment, order: create(:order))
end
Timecop.travel(@dt2) do
@shipment2 = create(:shipment, order: create(:order))
end
# Old shipment thats order was recently updated..
@order3 = create(:order, updated_at: @dt_now)
Timecop.travel(1.week.ago) do
@shipment3 = create(:shipment)
end
@shipment3.order = @order3
@shipment3.save!
@active << @shipment3
# End Old shipment thats order was recently updated..
@shipment4 = create(:shipment, order: create(:order))
@shipment5 = create(:shipment, order: create(:order))
# New shipments
@active << @shipment4
@active << @shipment5
end
# Get new shipments
from = Time.now - 1.hour
to = Time.now + 1.hour
subject(:shipments) { Spree::Shipment.between(from, to) }
specify { expect(shipments.size).to eq(@active.size) } # check the searching of the active shipments
shipments2 = Spree::Shipment.where(updated_at: from..to)
specify { expect(shipments2.size).to eq(@active.size) } # check the searching of the active shipments
specify { expect(@active.size).to eq(3) } # check size of the @active shipments
subject(:all_shipments) { Spree::Shipment.all }
specify { expect(all_shipments.size).to eq(5) } # check the total shipments
end
context "exportable" do
let!(:pending) { create_shipment(state: 'pending') }
let!(:ready) { create_shipment(state: 'ready') }
let!(:shipped) { create_shipment(state: 'shipped') }
subject { Spree::Shipment.exportable }
# specify { should have(2).shipments }
specify { expect(subject.count).to eq(2) }
specify { should include(ready) }
specify { should include(shipped) }
specify { should_not include(pending) }
end
context "shipped_email" do
let(:shipment) { create_shipment(state: 'ready') }
context "enabled" do
it "sends email" do
Spree::Config.send_shipped_email = true
mail_message = double(Mail::Message)
expect(Spree::ShipmentMailer).to receive(:shipped_email)
.with(shipment.id)
.and_return(mail_message)
expect(mail_message).to receive(:deliver_later)
shipment.ship!
end
end
context "disabled" do
it "doesnt send email" do
Spree::Config.send_shipped_email = false
expect(Spree::ShipmentMailer).not_to receive(:shipped_email)
shipment.ship!
end
end
end
def create_shipment(options={})
FactoryGirl.create(:shipment, options).tap do |shipment|
shipment.update_column(:state, options[:state]) if options[:state]
shipment.update_column(:updated_at, options[:updated_at]) if options[:updated_at]
end
end
end
|
charlie22c/spree_shipstation
|
spec/factories/order.rb
|
require 'spree/testing_support/factories'
FactoryGirl.modify do
factory :order, class: Spree::Order do
end
end
|
charlie22c/spree_shipstation
|
spec/factories/shipment.rb
|
<gh_stars>0
require 'spree/testing_support/factories'
require 'timecop'
FactoryGirl.modify do
factory :shipment, class: Spree::Shipment do
association :order
end
end
|
charlie22c/spree_shipstation
|
spec/lib/spree/shipment_notice_spec.rb
|
require 'spec_helper'
include Spree
describe Spree::ShipmentNotice do
let(:notice) { ShipmentNotice.new(order_number: 'S12345',
tracking_number: '1Z1231234') }
context "#apply" do
context "shipment found" do
let(:shipment) { mock_model(Shipment, :shipped? => false) }
before do
Spree::Config.shipstation_number = :shipment
Shipment.should_receive(:find_by_number).with('S12345').and_return(shipment)
shipment.should_receive(:update_attribute).with(:tracking, '1Z1231234')
end
context "transition succeeds" do
before do
shipment.stub_chain(:reload, :update_attribute).with(:state, 'shipped')
shipment.stub_chain(:inventory_units, :each)
shipment.should_receive(:touch).with(:shipped_at)
end
# specify { notice.apply.should be_true }
specify { expect(notice.apply).to be true }
end
context "transition fails" do
before do
shipment.stub_chain(:reload, :update_attribute)
.with(:state, 'shipped')
.and_raise('oopsie')
@result = notice.apply
end
specify { expect(@result).to be false }
#specify { notice.error.should_not be_blank }
specify { expect(notice.error).not_to be_empty }
end
end
context "using order number instead of shipment number" do
let(:shipment) { mock_model(Shipment, :shipped? => false) }
let(:order) { mock_model(Order, shipment: shipment) }
before do
Spree::Config.shipstation_number = :order
Order.should_receive(:find_by_number).with('S12345').and_return(order)
shipment.should_receive(:update_attribute).with(:tracking, '1Z1231234')
shipment.stub_chain(:inventory_units, :each)
shipment.should_receive(:touch).with(:shipped_at)
end
context "transition succeeds" do
before { shipment.stub_chain(:reload, :update_attribute).with(:state, 'shipped') }
# specify { notice.apply.should be_true }
specify { expect(notice.apply).to be true }
end
end
context "shipment not found" do
before do
Spree::Config.shipstation_number = :shipment
Shipment.should_receive(:find_by_number).with('S12345').and_return(nil)
@result = notice.apply
end
#specify { @result.should be_false }
specify { expect(@result).to be false }
# specify { notice.error.should_not be_blank }
# specify { expect(notice.error).to be_truthy }
specify { expect(notice.error).not_to be_blank }
end
context "shipment already shipped" do
let(:shipment) { mock_model(Shipment, :shipped? => true) }
before do
Spree::Config.shipstation_number = :shipment
Shipment.should_receive(:find_by_number).with('S12345').and_return(shipment)
shipment.should_receive(:update_attribute).with(:tracking, '1Z1231234')
end
#specify { notice.apply.should be_true }
specify { expect(notice.apply).to be true }
end
end
end
|
charlie22c/spree_shipstation
|
spec/support/factory_girl.rb
|
<gh_stars>0
# RSpec.configure do |config|
# # additional factory_girl configuration
#
# config.before(:suite) do
# begin
# DatabaseCleaner.start
# # builds each factory and subsequently calls #valid? on it (if #valid? is defined);
# # if any calls to #valid? return false, FactoryGirl::InvalidFactoryError is raised with a list of the offending factories.
# FactoryGirl.lint
# ensure
# DatabaseCleaner.clean
# end
# end
#
# # lint factories selectively by passing only factories you want linted
# factories_to_lint = FactoryGirl.factories.reject do |factory|
# factory.name =~ /^old_/
# end
#
# # This would lint all factories that aren't prefixed with old_.
# FactoryGirl.lint factories_to_lint
# end
|
charlie22c/spree_shipstation
|
spec/controllers/spree/shipstation_controller_spec.rb
|
require 'spec_helper'
describe Spree::ShipstationController, type: :controller do
before do
# controller.stub(check_authorization: false, spree_current_user: FactoryGirl.create(:user)) # TODO: uncomment and fix it
# controller.stub(:shipnotify)
@request.accept = 'application/xml'
end
context "logged in" do
before { login }
context "export" do
let(:shipments) { double(:shipments) }
describe "record retrieval" do
before do
Spree::Shipment.stub_chain(:exportable, :between).with(Time.new(2013, 12, 31, 8, 0, 0, "+00:00"),
Time.new(2014, 1, 13, 23, 0, 0, "+00:00"))
.and_return(shipments)
shipments.stub_chain(:page, :per).and_return(:some_shipments)
get :export, start_date: '12/31/2013 8:00', end_date: '1/13/2014 23:00', use_route: :spree
end
specify { expect(response).to be_success }
specify { expect(response).to have_http_status(200) }
specify { expect(assigns(:shipments)).to eq(:some_shipments) }
end
describe "XML output" do
render_views
let(:order) { create(:order_ready_to_ship) }
let(:shipment) { order.shipments.first }
before(:each) do
order.update_column(:updated_at, "2014-01-07")
shipment.update_column(:updated_at, "2014-01-07")
end
it "renders xml including the shipment number as OrderNumber by default" do
get :export, start_date: '12/31/2013 8:00', end_date: '1/13/2014 23:00', use_route: :spree
expect(response.body).to include("<OrderNumber>#{shipment.number}</OrderNumber>")
end
it "adds the orderID as custom field 1" do
get :export, start_date: '12/31/2013 8:00', end_date: '1/13/2014 23:00', use_route: :spree
expect(response.body).to include("<CustomField1>#{order.number}</CustomField1>")
end
context "with custom fields defined on the order" do
before(:each) do
module ShipstationCustom
def shipstation_custom_field_1
"custom1"
end
def shipstation_custom_field_2
"custom2"
end
def shipstation_custom_field_3
"custom3"
end
end
Spree::Order.class_eval do
include ShipstationCustom
end
end
it "honors custom fields defined on the order class" do
get :export, start_date: '12/31/2013 8:00', end_date: '1/13/2014 23:00', use_route: :spree
expect(response.body).to include("<CustomField1>custom1</CustomField1>")
expect(response.body).to include("<CustomField2>custom2</CustomField2>")
expect(response.body).to include("<CustomField3>custom3</CustomField3>")
end
end
context "with gift wrapping" do
before(:each) do
module GiftWrapExtension
def gift?
true
end
def gift_wrapping_message
"happy birthday"
end
end
Spree::Order.class_eval do
include GiftWrapExtension
end
end
it "honors custom fields defined on the order class" do
get :export, start_date: '12/31/2013 8:00', end_date: '1/13/2014 23:00', use_route: :spree
expect(response.body).to include("<Gift>true</Gift>")
expect(response.body).to include("<GiftMessage>happy birthday</GiftMessage>")
end
end
end
end
context "shipnotify" do
let(:notice) { double(:notice) }
before do
Spree::ShipmentNotice.should_receive(:new)
.with(hash_including(order_number: 'S12345'))
.and_return(notice)
end
context "shipment found" do
before do
notice.should_receive(:apply).and_return(true)
post :shipnotify, order_number: 'S12345', use_route: :spree
end
# specify { response.should be_success }
# specify { response.body.should =~ /success/ }
specify { expect(response).to be_success }
# specify { expect(response.body).to match(/success/) }
specify { expect(response).to render_template("shipnotify") }
end
context "shipment not found" do
before do
notice.should_receive(:apply).and_return(false)
notice.should_receive(:error).and_return("failed")
post :shipnotify, order_number: 'S12345', use_route: :spree
end
# specify { response.code.should == '400' }
# specify { response.body.should =~ /failed/ }
specify { expect(response.code).to eq('400') }
# specify { expect(response.body).to match(/failed/) }
specify { expect(response).to render_template("shipnotify") }
end
end
it "doesnt know unknown" do
expect { post :unknown, use_route: :spree }.to raise_error(AbstractController::ActionNotFound)
end
end
context "not logged in" do
it "returns error" do
get :export, use_route: :spree
#response.code.should == '401'
expect(response.code).to eq('401')
end
end
def login
user, pw = '<PASSWORD>', '<PASSWORD>'
config(username: user, password: pw)
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(user, pw)
end
def config(options = {})
options.each do |k, v|
Spree::Config.send("shipstation_#{k}=", v)
end
end
end
|
charlie22c/spree_shipstation
|
app/controllers/spree/shipstation_controller.rb
|
<reponame>charlie22c/spree_shipstation<filename>app/controllers/spree/shipstation_controller.rb
include SpreeShipstation
module Spree
class ShipstationController < Spree::BaseController
#include BasicSslAuthentication
include Spree::DateParamHelper
skip_before_filter :verify_authenticity_token
before_filter :authenticate
def authenticate
authenticate_or_request_with_http_basic('Authentication Required') do |username, password|
username == Spree::Config.shipstation_username && password == Spree::Config.shipstation_password
end
end
layout false
def export
@page_size = Spree::Config.shipstation_page_size
@shipments = Spree::Shipment.exportable.between(date_param(:start_date), date_param(:end_date)).page(params[:page]).per(@page_size)
end
def shipnotify
@notice = notice = Spree::ShipmentNotice.new(params)
number = params[:order_number]
shipment = Spree::Shipment.find_by_number(number)
if shipment
order = shipment.order
order.shipment_state = 'shipped'
order.save!
end
Ns::Jobs::ShipmentShippedWorker.perform_async(number)
if notice.apply
@text = 'success'
respond_to do |format|
format.html { render(text: @text, status: :ok) }
format.xml { render template: "spree/shipstation/shipnotify", status: :ok }
format.json { render json: {text: @text, status: :ok} }
end
else
@text = notice.error
respond_to do |format|
format.html { render(@text, status: :bad_request) }
format.xml { render template: "spree/shipstation/shipnotify", status: :bad_request }
format.json { render json: {text: @text, status: :bad_request} }
end
end
end
end
end
|
charlie22c/spree_shipstation
|
app/views/spree/shipstation/shipnotify.xml.builder
|
xml.instruct!
xml.text @text
|
Talkdesk/jruby
|
spec/ruby/library/readline/spec_helper.rb
|
require File.expand_path('../../../spec_helper', __FILE__)
unless MSpec.retrieve(:features).key?(:readline)
begin
require 'readline'
rescue LoadError
else
# rb-readline behaves quite differently
if $".grep(/\brbreadline\.rb$/).empty?
MSpec.enable_feature :readline
end
end
end
|
Talkdesk/jruby
|
spec/ruby/language/undef_spec.rb
|
require File.expand_path('../../spec_helper', __FILE__)
describe "The undef keyword" do
describe "undefines a method" do
before :each do
@undef_class = Class.new do
def meth(o); o; end
end
@obj = @undef_class.new
@obj.meth(5).should == 5
end
it "with an identifier" do
@undef_class.class_eval do
undef meth
end
lambda { @obj.meth(5) }.should raise_error(NoMethodError)
end
it "with a simple symbol" do
@undef_class.class_eval do
undef :meth
end
lambda { @obj.meth(5) }.should raise_error(NoMethodError)
end
it "with a single quoted symbol" do
@undef_class.class_eval do
undef :'meth'
end
lambda { @obj.meth(5) }.should raise_error(NoMethodError)
end
it "with a double quoted symbol" do
@undef_class.class_eval do
undef :"meth"
end
lambda { @obj.meth(5) }.should raise_error(NoMethodError)
end
it "with a interpolated symbol" do
@undef_class.class_eval do
undef :"#{'meth'}"
end
lambda { @obj.meth(5) }.should raise_error(NoMethodError)
end
end
it "allows undefining multiple methods at a time" do
undef_multiple = Class.new do
def method1; end
def method2; :nope; end
undef :method1, :method2
end
obj = undef_multiple.new
obj.respond_to?(:method1).should == false
obj.respond_to?(:method2).should == false
end
it "raises a NameError when passed a missing name" do
Class.new do
lambda {
undef not_exist
}.should raise_error(NameError) { |e|
# a NameError and not a NoMethodError
e.class.should == NameError
}
end
end
end
|
Talkdesk/jruby
|
spec/mspec/lib/mspec/matchers/be_nil.rb
|
<reponame>Talkdesk/jruby<filename>spec/mspec/lib/mspec/matchers/be_nil.rb
class BeNilMatcher
def matches?(actual)
@actual = actual
@actual.nil?
end
def failure_message
["Expected #{@actual.inspect}", "to be nil"]
end
def negative_failure_message
["Expected #{@actual.inspect}", "not to be nil"]
end
end
class Object
def be_nil
BeNilMatcher.new
end
end
|
Talkdesk/jruby
|
spec/ruby/optional/capi/spec_helper.rb
|
require File.expand_path('../../../spec_helper', __FILE__)
$extmk = false
require 'rbconfig'
OBJDIR ||= File.expand_path("../../../ext/#{RUBY_NAME}/#{RUBY_VERSION}", __FILE__)
mkdir_p(OBJDIR)
def extension_path
File.expand_path("../ext", __FILE__)
end
def object_path
OBJDIR
end
def compile_extension(name)
preloadenv = RbConfig::CONFIG["PRELOADENV"] || "LD_PRELOAD"
preload, ENV[preloadenv] = ENV[preloadenv], nil if preloadenv
path = extension_path
objdir = object_path
# TODO use rakelib/ext_helper.rb?
arch_hdrdir = nil
if RUBY_NAME == 'rbx'
hdrdir = RbConfig::CONFIG["rubyhdrdir"]
elsif RUBY_NAME =~ /^ruby/
hdrdir = RbConfig::CONFIG["rubyhdrdir"]
arch_hdrdir = RbConfig::CONFIG["rubyarchhdrdir"]
elsif RUBY_NAME == 'jruby'
require 'mkmf'
hdrdir = $hdrdir
elsif RUBY_NAME == "maglev"
require 'mkmf'
hdrdir = $hdrdir
elsif RUBY_NAME == 'truffleruby'
return compile_truffleruby_extconf_make(name, path, objdir)
else
raise "Don't know how to build C extensions with #{RUBY_NAME}"
end
ext = "#{name}_spec"
source = File.join(path, "#{ext}.c")
obj = File.join(objdir, "#{ext}.#{RbConfig::CONFIG['OBJEXT']}")
lib = File.join(objdir, "#{ext}.#{RbConfig::CONFIG['DLEXT']}")
ruby_header = File.join(hdrdir, "ruby.h")
rubyspec_header = File.join(path, "rubyspec.h")
return lib if File.exist?(lib) and File.mtime(lib) > File.mtime(source) and
File.mtime(lib) > File.mtime(ruby_header) and
File.mtime(lib) > File.mtime(rubyspec_header) and
true # sentinel
# avoid problems where compilation failed but previous shlib exists
File.delete lib if File.exist? lib
cc = RbConfig::CONFIG["CC"]
cflags = (ENV["CFLAGS"] || RbConfig::CONFIG["CFLAGS"]).dup
cflags += " #{RbConfig::CONFIG["ARCH_FLAG"]}" if RbConfig::CONFIG["ARCH_FLAG"]
cflags += " #{RbConfig::CONFIG["CCDLFLAGS"]}" if RbConfig::CONFIG["CCDLFLAGS"]
cppflags = (ENV["CPPFLAGS"] || RbConfig::CONFIG["CPPFLAGS"]).dup
incflags = "-I#{path}"
incflags << " -I#{arch_hdrdir}" if arch_hdrdir
incflags << " -I#{hdrdir}"
csrcflag = RbConfig::CONFIG["CSRCFLAG"]
coutflag = RbConfig::CONFIG["COUTFLAG"]
compile_cmd = "#{cc} #{incflags} #{cflags} #{cppflags} #{coutflag}#{obj} -c #{csrcflag}#{source}"
output = `#{compile_cmd}`
unless $?.success? and File.exist?(obj)
puts "\nERROR:\n#{compile_cmd}\n#{output}"
puts "incflags=#{incflags}"
puts "cflags=#{cflags}"
puts "cppflags=#{cppflags}"
raise "Unable to compile \"#{source}\""
end
ldshared = RbConfig::CONFIG["LDSHARED"]
ldshared += " #{RbConfig::CONFIG["ARCH_FLAG"]}" if RbConfig::CONFIG["ARCH_FLAG"]
libs = RbConfig::CONFIG["LIBS"]
dldflags = "#{RbConfig::CONFIG["LDFLAGS"]} #{RbConfig::CONFIG["DLDFLAGS"]} #{RbConfig::CONFIG["EXTDLDFLAGS"]}"
dldflags.sub!(/-Wl,-soname,\S+/, '')
if /mswin/ =~ RUBY_PLATFORM
dldflags.sub!("$(LIBPATH)", RbConfig::CONFIG["LIBPATHFLAG"] % path)
libs += RbConfig::CONFIG["LIBRUBY"]
outflag = RbConfig::CONFIG["OUTFLAG"]
link_cmd = "#{ldshared} #{outflag}#{lib} #{obj} #{libs} -link #{dldflags} /export:Init_#{ext}"
else
libpath = "-L#{path}"
dldflags.sub!("$(TARGET_ENTRY)", "Init_#{ext}")
link_cmd = "#{ldshared} #{obj} #{libpath} #{dldflags} #{libs} -o #{lib}"
end
output = `#{link_cmd}`
unless $?.success?
puts "\nERROR:\n#{link_cmd}\n#{output}"
raise "Unable to link \"#{source}\""
end
lib
ensure
ENV[preloadenv] = preload if preloadenv
end
def compile_truffleruby_extconf_make(name, path, objdir)
ext = "#{name}_spec"
file = "#{ext}.c"
source = "#{path}/#{ext}.c"
lib = "#{objdir}/#{ext}.#{RbConfig::CONFIG['DLEXT']}"
# Copy needed source files to tmpdir
tmpdir = tmp("cext_#{name}")
Dir.mkdir tmpdir
begin
["rubyspec.h", "truffleruby.h", "#{ext}.c"].each do |file|
cp "#{path}/#{file}", "#{tmpdir}/#{file}"
end
Dir.chdir(tmpdir) do
required = require 'mkmf'
# Reinitialize mkmf if already required
init_mkmf unless required
create_makefile(ext, tmpdir)
system "make"
copy_exts = RbConfig::CONFIG.values_at('OBJEXT', 'DLEXT')
Dir.glob("*.{#{copy_exts.join(',')}}") do |file|
cp file, "#{objdir}/#{file}"
end
end
ensure
rm_r tmpdir
end
lib
end
def load_extension(name)
require compile_extension(name)
rescue LoadError
if %r{/usr/sbin/execerror ruby "\(ld 3 1 main ([/a-zA-Z0-9_\-.]+_spec\.so)"} =~ $!.message
system('/usr/sbin/execerror', "#{RbConfig::CONFIG["bindir"]}/ruby", "(ld 3 1 main #{$1}")
end
raise
end
# Constants
CAPI_SIZEOF_LONG = [0].pack('l!').size
|
gunyarakun/cookie-clicker-generator
|
app/models/cookie_clicker.rb
|
class CookieClicker < ActiveRecord::Base
acts_as_paranoid
belongs_to :user
has_many :images
validates_presence_of :title, :user_id
attr_accessible :title, :user_id, :published
def image_paths
paths = {}
CookieClickerGenerator::Application::CC_IMAGES.keys.each do |filename|
paths[filename] = "/cookie-clicker/img/#{filename}"
end
images.each do |image|
if image.body
paths[image.path] = image.body.url
end
end
paths
end
end
|
gunyarakun/cookie-clicker-generator
|
test/helpers/cookie_clickers_helper_test.rb
|
require 'test_helper'
class CookieClickersHelperTest < ActionView::TestCase
end
|
gunyarakun/cookie-clicker-generator
|
lib/tasks/unicorn.rake
|
# coding: utf-8
# This rake task is from
# http://www.techscore.com/blog/2012/10/19/custom-unicorn-rake-tasks/
namespace :unicorn do
UNICORN_CONFIG_FILE_PATH = Rails.root.join('config', 'unicorn.rb')
UNICORN_PID_FILE_PATH = Rails.root.join('tmp', 'pids', 'unicorn.pid')
def unicorn_master_pid_string
pid_file_path = UNICORN_PID_FILE_PATH
return nil unless File.exists?(pid_file_path)
pid_string = `ps h -o pid,command #{File.read(pid_file_path).to_i}`.strip
return nil unless pid_string.present?
pid_string
end
def unicorn_master_pid
pid_string = unicorn_master_pid_string
return nil unless pid_string
pid_string.to_i
end
def unicorn_worker_pid_strings
pid = unicorn_master_pid
return nil unless pid
`ps h -o pid,command --ppid #{pid}`.split(/\n/).map(&:strip)
end
def unicorn_worker_pids
pid_strings = unicorn_worker_pid_strings
return nil unless pid_strings
pid_strings.map(&:to_i)
end
def unicorn_pid_strings
pid_strings = [unicorn_master_pid_string, unicorn_worker_pid_strings].flatten.compact
return nil unless pid_strings.present?
pid_strings
end
def unicorn_pids
pid_strings = unicorn_pid_strings
return nil unless pid_strings
pid_strings.map(&:to_i)
end
def send_signal_to_unicorn_master(signal, failed_message='Not running.')
if pid = unicorn_master_pid
Process.kill(signal, pid)
else
puts failed_message if failed_message.present?
end
end
desc 'Show unicorn process-pids.'
task(:pids) { puts (unicorn_pid_strings || 'Not running.') }
desc 'Start unicorn server.'
task(:start) { system("unicorn -c '#{UNICORN_CONFIG_FILE_PATH}' -E #{Rails.env} -D") }
desc 'Reloads config file and gracefully restart all workers (Send signal HUP to master process).'
task(:graceful) { send_signal_to_unicorn_master(:HUP) }
desc 'Quick shutdown, kills all workers immediately (Send signal TERM to master process).'
task(:kill) { send_signal_to_unicorn_master(:TERM) }
desc 'Graceful shutdown (Send signal QUIT to master process).'
task(:stop) { send_signal_to_unicorn_master(:QUIT) }
desc 'Reopen all logs owned by the master and all workers (Send signal USR1 to master process).'
task(:reopen_logs) { send_signal_to_unicorn_master(:USR1) }
desc 'Reexecute the running binary (Send signal USR2 to master process).'
task(:restart) { send_signal_to_unicorn_master(:USR2) }
desc 'Gracefully stops workers but keep the master running (Send signal WINCH to master process).'
task('workers:stop') { send_signal_to_unicorn_master(:WINCH) }
desc 'Increment the number of worker processes by one (Send signal TTIN to master process).'
task('workers:increment') { send_signal_to_unicorn_master(:TTIN) }
desc 'Decrement the number of worker processes by one (Send signal TTOU to master process).'
task('workers:decrement') { send_signal_to_unicorn_master(:TTOU) }
def worker_number_pid_name_triples
number_pid_name_triples = (unicorn_worker_pid_strings || []).flatten.map do |line|
pid, name = *line.split(' ').values_at(0, 2)
number = name.gsub(/\D/, '')
[number.to_i, pid.to_i, name]
end
number_pid_name_triples.sort
end
worker_number_pid_name_triples.each do |number, pid, name|
desc "Quick shutdown, immediately exit (Send signal TERM to #{name} process)."
task("worker#{number}:kill") { Process.kill(:TERM, pid) }
desc "Gracefully exit after finishing the current request (Send signal QUIT to #{name} process)."
task("worker#{number}:stop") { Process.kill(:QUIT, pid) }
desc "Reopen all logs owned by the worker process (Send signal USR1 to #{name} process)."
task("worker#{number}:reopen_logs") { Process.kill(:USR1, pid) }
desc "Output thread dump (Send signal USR2 to #{name} process)."
task("worker#{number}:thread_dump") { Process.kill(:USR2, pid) }
end
end if defined?(Unicorn)
|
gunyarakun/cookie-clicker-generator
|
config/initializers/twitter.rb
|
Twitter.configure do |config|
config.consumer_key = Settings.twitter.consumer_key
config.consumer_secret = Settings.twitter.consumer_secret
end
|
gunyarakun/cookie-clicker-generator
|
db/migrate/20130921064812_create_images.rb
|
<filename>db/migrate/20130921064812_create_images.rb
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :path
t.integer :user_id # NOTE: This is duplicated column
t.integer :cookie_clicker_id
t.string :external_source # for easy mode like '@tasukuchan'
t.string :external_url # for easy mode
t.datetime :deleted_at # for rails4_acts_as_paranoid
t.timestamps
end
add_index :images, [:cookie_clicker_id, :path], :unique => true
add_index :images, :user_id
end
end
|
gunyarakun/cookie-clicker-generator
|
app/models/user.rb
|
<reponame>gunyarakun/cookie-clicker-generator
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
# devise :database_authenticatable, :registerable,
# :recoverable, :rememberable, :trackable, :validatable
devise :trackable, :omniauthable
attr_accessible :name, :password, :uid, :provider
def self.new_with_session(params, session)
super.tap do |user|
if data = session['devise.facebook_data'] && session['devise.facebook_data']['extra']['raw_info']
user.email = data['email']
end
end
end
def self.find_for_twitter_oauth(auth, signed_in_resource = nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(name: auth.info.nickname,
provider: auth.provider,
uid: auth.uid,
# email:
password: <PASSWORD>[0, 20]
)
end
# Save oauth token/secret per login
user.oauth_token = auth.credentials.token
user.oauth_token_secret = auth.credentials.secret
user.save
user
end
def twitter_friends
twit = Twitter::Client.new(
:oauth_token => oauth_token,
:oauth_token_secret => oauth_token_secret
)
# TODO: use cursor
twit.friends
end
end
|
gunyarakun/cookie-clicker-generator
|
config/initializers/session_store.rb
|
<filename>config/initializers/session_store.rb
# Be sure to restart your server when you modify this file.
CookieClickerGenerator::Application.config.session_store :cookie_store, key: '_cookie-clicker-generator_session'
|
gunyarakun/cookie-clicker-generator
|
test/controllers/cookie_clickers_controller_test.rb
|
require 'test_helper'
class CookieClickersControllerTest < ActionController::TestCase
setup do
@cookie_clicker = cookie_clickers(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:cookie_clickers)
end
test "should get new" do
get :new
assert_response :success
end
test "should create cookie_clicker" do
assert_difference('CookieClicker.count') do
post :create, cookie_clicker: { }
end
assert_redirected_to cookie_clicker_path(assigns(:cookie_clicker))
end
test "should show cookie_clicker" do
get :show, id: @cookie_clicker
assert_response :success
end
test "should get edit" do
get :edit, id: @cookie_clicker
assert_response :success
end
test "should update cookie_clicker" do
patch :update, id: @cookie_clicker, cookie_clicker: { }
assert_redirected_to cookie_clicker_path(assigns(:cookie_clicker))
end
test "should destroy cookie_clicker" do
assert_difference('CookieClicker.count', -1) do
delete :destroy, id: @cookie_clicker
end
assert_redirected_to cookie_clickers_path
end
end
|
gunyarakun/cookie-clicker-generator
|
config/initializers/paperclip.rb
|
module Paperclip
module Interpolations
def user_id(attachment, style_name)
attachment.instance.user_id.to_s
end
def cookie_clicker_id(attachment, style_name)
attachment.instance.cookie_clicker_id.to_s
end
end
end
|
gunyarakun/cookie-clicker-generator
|
db/schema.rb
|
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20130921065337) do
create_table "cookie_clickers", force: true do |t|
t.integer "user_id"
t.string "title", limit: 128
t.boolean "published"
t.boolean "easy_mode"
t.datetime "deleted_at"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "cookie_clickers", ["updated_at", "published"], name: "index_cookie_clickers_on_updated_at_and_published", using: :btree
create_table "images", force: true do |t|
t.string "path"
t.integer "user_id"
t.integer "cookie_clicker_id"
t.string "external_source"
t.string "external_url"
t.datetime "deleted_at"
t.datetime "created_at"
t.datetime "updated_at"
t.string "body_file_name"
t.string "body_content_type"
t.integer "body_file_size"
t.datetime "body_updated_at"
end
add_index "images", ["cookie_clicker_id", "path"], name: "index_images_on_cookie_clicker_id_and_path", unique: true, using: :btree
add_index "images", ["user_id"], name: "index_images_on_user_id", using: :btree
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "oauth_token"
t.string "oauth_token_secret"
t.datetime "created_at"
t.datetime "updated_at"
t.string "uid"
t.string "name"
t.string "provider"
t.string "password"
end
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
end
|
gunyarakun/cookie-clicker-generator
|
app/helpers/application_helper.rb
|
module ApplicationHelper
def cc_image_resize(name, max_width = CookieClickerGenerator::Application::THUMBNAIL_MAX_PIXELS, max_height = CookieClickerGenerator::Application::THUMBNAIL_MAX_PIXELS)
cc_image_info = CookieClickerGenerator::Application::CC_IMAGES[name]
if cc_image_info
w_ratio = max_width * 1.0 / cc_image_info[:width]
h_ratio = max_height * 1.0 / cc_image_info[:height]
if w_ratio > 1.0 and h_ratio > 1.0
return { :width => cc_image_info[:width], :height => cc_image_info[:height] }
elsif w_ratio < h_ratio
return {
:width => (cc_image_info[:width] * w_ratio).to_i,
:height => (cc_image_info[:height] * w_ratio).to_i
}
else
return {
:width => (cc_image_info[:width] * h_ratio).to_i,
:height => (cc_image_info[:height] * h_ratio).to_i
}
end
else
return {
:width => 0,
:height => 0,
}
end
end
end
|
gunyarakun/cookie-clicker-generator
|
config/unicorn.rb
|
worker_processes 4
listen '/tmp/unicorn.sock', :backlog => 1
listen 8080, :tcp_nopush => true
stderr_path File.expand_path('../../log/unicorn/stderr.log', __FILE__)
stdout_path File.expand_path('../../log/unicorn/stdout.log', __FILE__)
pid File.expand_path('../../tmp/pids/unicorn.pid', __FILE__)
preload_app false
|
gunyarakun/cookie-clicker-generator
|
app/models/image.rb
|
<reponame>gunyarakun/cookie-clicker-generator<filename>app/models/image.rb
class Image < ActiveRecord::Base
acts_as_paranoid
belongs_to :user
belongs_to :cookie_clicker
validates_presence_of :user_id, :cookie_clicker_id, :path
# validates_attachment_presence :body
attr_accessible :path, :cookie_clicker_id, :body
validates_inclusion_of :path, :in => CookieClickerGenerator::Application::CC_IMAGES.keys
has_attached_file :body,
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => ":user_id/:cookie_clicker_id/:id.:extension",
:processor => 'mini_magick',
:styles => {:original => '100%'},
:convert_options => {
:original => lambda {|attachment|
"-resize '#{attachment.cc_image_size}' -background none -compose Copy -gravity center -extent #{attachment.cc_image_size}"
}
}
def body_url
if body.present?
body.url
else
nil
end
end
def cc_image_size
image_info = CookieClickerGenerator::Application::CC_IMAGES[path]
"#{image_info[:width]}x#{image_info[:height]}"
end
def cc_image_format
image_info = CookieClickerGenerator::Application::CC_IMAGES[path]
image_info[:format]
end
end
|
gunyarakun/cookie-clicker-generator
|
app/views/images/show.json.jbuilder
|
json.extract! @image, :path, :body
if @image.body.present?
thumb_size = cc_image_resize(@image.path)
json.set! :thumb_width, thumb_size[:width]
json.set! :thumb_height, thumb_size[:height]
end
|
gunyarakun/cookie-clicker-generator
|
app/controllers/root_controller.rb
|
class RootController < ApplicationController
def index
@cookie_clickers = CookieClicker.where(:published => true).order('created_at desc').page(params[:page])
respond_to do |format|
format.html
format.js
end
end
end
|
gunyarakun/cookie-clicker-generator
|
config/application.rb
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module CookieClickerGenerator
class Application < Rails::Application
# 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.
# 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. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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}').to_s]
config.i18n.default_locale = :en
THUMBNAIL_MAX_PIXELS = 200
CC_IMAGES = {
# favicon.ico
'favicon.ico' => {
:format => 'ico',
:width => 16,
:height => 16,
},
# Setsubi
'cursoricon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'grandmaIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'farmIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'factoryIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'mineIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'shipmentIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'alchemylabIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'portalIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'timemachineIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'antimattercondenserIcon.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
# Field items
'cursor.png' => {
:format => 'png',
:width => 32,
:height => 32,
},
'farm.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'factory.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'mine.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'shipment.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'alchemylab.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'portal.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'timemachine.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'antimattercondenser.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
# Backgrounds for field
'grandmaBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'farmBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'factoryBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'mineBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'shipmentBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'alchemylabBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'portalBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'timemachineBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'antimattercondenserBackground.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
# grandma
'grandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'farmerGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'workerGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'minerGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'cosmicGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'transmutedGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'alteredGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'grandmasGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'antiGrandma.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'mysteriousHero.png' => {
:format => 'png',
:width => 96,
:height => 96,
},
'mysteriousOpponent.png' => {
:format => 'png',
:width => 96,
:height => 96,
},
# granmas backgrounds
'grandmas1.jpg' => {
:format => 'jpg',
:width => 256,
:height => 256,
},
'grandmas2.jpg' => {
:format => 'jpg',
:width => 256,
:height => 256,
},
'grandmas3.jpg' => {
:format => 'jpg',
:width => 256,
:height => 256,
},
# Cookie/Golden Cookie
'perfectCookie.png' => {
:format => 'png',
:width => 512,
:height => 512,
},
'imperfectCookie.png' => {
:format => 'png',
:width => 512,
:height => 512,
},
'shine.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'goldCookie.png' => {
:format => 'png',
:width => 96,
:height => 96,
},
'wrathCookie.png' => {
:format => 'png',
:width => 96,
:height => 96,
},
'smallCookies.png' => {
:format => 'png',
:width => 512,
:height => 64,
},
'money.png' => {
:format => 'png',
:width => 16,
:height => 16,
},
'cookieShower1.png' => {
:format => 'png',
:width => 512,
:height => 512,
},
'cookieShower2.png' => {
:format => 'png',
:width => 512,
:height => 512,
},
'cookieShower3.png' => {
:format => 'png',
:width => 512,
:height => 512,
},
# milk
'milk.png' => {
:format => 'png',
:width => 480,
:height => 640,
},
'milkWave.png' => {
:format => 'png',
:width => 480,
:height => 480,
},
'chocolateMilkWave.png' => {
:format => 'png',
:width => 480,
:height => 480,
},
'raspberryWave.png' => {
:format => 'png',
:width => 480,
:height => 480,
},
# Panel/Frames
'panelHorizontal.png' => {
:format => 'png',
:width => 640,
:height => 16,
},
'panelVertical.png' => {
:format => 'png',
:width => 16,
:height => 640,
},
'upgradeFrame.png' => {
:format => 'png',
:width => 60,
:height => 60,
},
# Backgrounds
'bgBlue.jpg' => {
:format => 'png',
:width => 600,
:height => 600,
},
'storeTile.jpg' => {
:format => 'png',
:width => 300,
:height => 256,
},
# misc
'icons.png' => {
:format => 'png',
:width => 960,
:height => 576,
},
'blackGradient.png' => {
:format => 'png',
:width => 2,
:height => 640,
},
'control.png' => {
:format => 'png',
:width => 144,
:height => 144,
},
'darkNoise.png' => {
:format => 'png',
:width => 64,
:height => 64,
},
'infoBG.png' => {
:format => 'png',
:width => 16,
:height => 16,
},
'infoBGfade.png' => {
:format => 'png',
:width => 16,
:height => 16,
},
'mapBG.jpg' => {
:format => 'jpg',
:width => 600,
:height => 600,
},
'mapIcons.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'mapTiles.png' => {
:format => 'png',
:width => 128,
:height => 128,
},
'marshmallows.png' => {
:format => 'png',
:width => 192,
:height => 64,
},
}
CC_LANGS = {
'ja' => {
desc: 'Japanese',
},
'en' => {
desc: 'English',
}
}
end
end
|
gunyarakun/cookie-clicker-generator
|
db/migrate/20130921051234_create_cookie_clickers.rb
|
class CreateCookieClickers < ActiveRecord::Migration
def change
create_table :cookie_clickers do |t|
t.integer :user_id
t.string :title, :limit => 128
t.boolean :published
t.boolean :easy_mode
t.datetime :deleted_at # for rails4_acts_as_paranoid
t.timestamps
end
add_index :cookie_clickers, [:updated_at, :published]
end
end
|
gunyarakun/cookie-clicker-generator
|
app/controllers/images_controller.rb
|
require 'mini_magick'
class ImagesController < ApplicationController
before_action :set_image, only: [:update, :destroy]
before_filter :authenticate_user!
# POST /images
# POST /images.json
def create
@image = Image.new(image_params)
@image.user_id = current_user.id
respond_to do |format|
if @image.save
format.json { render action: 'show', status: :ok, location: @image }
else
format.json { render json: @image.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /images/1
# PATCH/PUT /images/1.json
def update
respond_to do |format|
if @image.update(image_params)
format.json { render action: 'show', status: :ok, location: @image }
else
format.json { render json: @image.errors, status: :unprocessable_entity }
end
end
end
# DELETE /images/1
# DELETE /images/1.json
def destroy
@image.destroy
respond_to do |format|
format.html { redirect_to images_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_image
@image = Image.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def image_params
params.require(:image).permit(:path, :cookie_clicker_id, :body)
end
def resize_cc_image(path, image)
end
end
|
gunyarakun/cookie-clicker-generator
|
lib/renders.rb
|
ActionController.add_renderer :css do |template, options|
string = render_to_string template, options
self.content_type ||= Mime::CSS
self.response_body = string
end
|
gunyarakun/cookie-clicker-generator
|
app/controllers/cookie_clickers_controller.rb
|
<reponame>gunyarakun/cookie-clicker-generator<filename>app/controllers/cookie_clickers_controller.rb
class CookieClickersController < ApplicationController
before_action :set_cookie_clicker_editable, only: [:edit, :update, :destroy]
before_action :set_cookie_clicker, only: [:show, :style, :main, :lang]
before_action :authenticate_user!, :except => [:show, :style, :main, :lang]
helper_method :cc_image_url, :cc_lang_base_url, :cc_image_map
def cc_image_url(filename)
# TODO: check CookieClickerGenerator::Application::CC_IMAGES[filename]
images = Image.where(cookie_clicker_id: @cookie_clicker.id, path: filename)
if images.count > 0
image = images[0]
if image and image.body
return image.body.url
end
end
"/cookie-clicker/img/#{filename}"
end
def cc_lang_base_url
"/cookie-clicker/lang/"
end
def cc_image_map
@cookie_clicker.image_paths
end
# GET /cookie_clickers
# GET /cookie_clickers.json
def index
@cookie_clickers = CookieClicker.where(:user_id => current_user.id)
end
# GET /cookie_clickers/1/
def show
render :layout => false
end
# GET /cookie_clickers/style.css
def style
respond_to do |format|
format.css
end
end
# GET /cookie_clickers/main.js
def main
@supported_languages = []
CookieClickerGenerator::Application::CC_LANGS.each_pair do |lang, info|
@supported_languages << [
lang, # lang (ex. 'ja'/'en')
info[:desc], # desc
I18n.locale == lang.intern, # default language
]
end
respond_to do |format|
format.js
end
end
# GET /cookie_clickers/:id/lang/:lang.js
def lang
# TODO: add lang model
lang = params[:lang]
if CookieClickerGenerator::Application::CC_LANGS.has_key?(lang)
render_template(:file => "#{Rails.root}/public/cookie-clicker/lang/#{lang}.js")
end
end
# GET /cookie_clickers/new
def new
@cookie_clicker = CookieClicker.new(:user_id => current_user.id)
end
# GET /cookie_clickers/1/edit
def edit
if @cookie_clicker.user_id != current_user.id
redirect_to :action => 'index'
end
user_images = Image.where(cookie_clicker_id: @cookie_clicker.id)
@cc_images = {}
images = CookieClickerGenerator::Application::CC_IMAGES
images.each_pair do |filename, image_info|
@cc_images[filename] = image_info.clone
end
user_images.each do |user_image|
if @cc_images.has_key?(user_image.path)
@cc_images[user_image.path][:user_image] = user_image
else
# invalid
end
end
end
# POST /cookie_clickers
# POST /cookie_clickers.json
def create
@cookie_clicker = CookieClicker.new(cookie_clicker_params)
@cookie_clicker.user_id = current_user.id
respond_to do |format|
if @cookie_clicker.save
format.html { redirect_to :action => 'index', notice: 'Cookie clicker was successfully created.' }
format.json { render action: 'show', status: :created, location: @cookie_clicker }
else
format.html { render action: 'new' }
format.json { render json: @cookie_clicker.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cookie_clickers/1
# PATCH/PUT /cookie_clickers/1.json
def update
respond_to do |format|
if @cookie_clicker.update(cookie_clicker_params)
format.html { redirect_to cookie_clickers_path, notice: 'Cookie clicker was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @cookie_clicker.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cookie_clickers/1
# DELETE /cookie_clickers/1.json
def destroy
@cookie_clicker.destroy
respond_to do |format|
format.html { redirect_to cookie_clickers_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cookie_clicker
@cookie_clicker = CookieClicker.find(params[:id])
end
def set_cookie_clicker_editable
@cookie_clicker = CookieClicker.find(params[:id])
if current_user.id != @cookie_clicker.user_id
redirect_to cookie_clickers_path(params[:id], :trailing_slash => true) and return
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def cookie_clicker_params
params.require(:cookie_clicker).permit(:title, :published)
end
end
|
mokos/open_uri_cache
|
spec/open_uri_cache_spec.rb
|
#!ruby -Ku
# coding: utf-8
require 'open_uri_cache'
require 'tmpdir'
require 'kconv'
RSpec.describe OpenUriCache do
it "has a version number" do
expect(OpenUriCache::VERSION).not_to be nil
end
it 'same result with cache' do
Dir.mktmpdir {|tmpdir|
url = 'https://twitter.com'
doc = OpenUriCache.open(url, cache_dir: tmpdir, after: 10)
doc2 = OpenUriCache.open(url, cache_dir: tmpdir, after: 10)
expect(doc.read).to eq doc2.read
}
end
it 'different result without chache' do
Dir.mktmpdir {|tmpdir|
url = 'https://twitter.com'
doc = OpenUriCache.open(url, cache_dir: tmpdir, after: 1)
# キャッシュ期間が1秒間
# 3秒間スリープするので次回openはキャッシュが効かない
sleep(3)
doc2 = OpenUriCache.open(url, cache_dir: tmpdir, after: 10)
expect(doc.read).not_to eq doc2.read
}
end
it 'no expiration' do
Dir.mktmpdir {|tmpdir|
url = 'https://twitter.com'
OpenUriCache.open(url, cache_dir: tmpdir)
OpenUriCache.open(url, cache_dir: tmpdir)
}
end
it 'return Tmpfile object if no cache, CacheFile if cache' do
Dir.mktmpdir {|tmpdir|
url = 'https://twitter.com'
doc = OpenUriCache.open(url, cache_dir: tmpdir)
expect(doc.class).to eq Tempfile
doc = OpenUriCache.open(url, cache_dir: tmpdir)
expect(doc.class).to eq OpenUriCache::CacheFile
}
end
it 'can access open-uri like method' do
Dir.mktmpdir {|tmpdir|
url = 'https://twitter.com'
OpenUriCache.open(url, cache_dir: tmpdir)
doc = OpenUriCache.open(url, cache_dir: tmpdir)
puts doc.class
puts doc.base_uri
puts doc.expiration
puts doc.charset
puts doc.content_encoding
puts doc.content_type
puts doc.last_modified
puts doc.status
}
end
it 'sleep when no cache, no sleep when cache' do
Dir.mktmpdir {|tmpdir|
sleep_sec = 1
url = 'https://twitter.com'
t = Time.now
OpenUriCache.open(url, cache_dir: tmpdir, sleep_sec: sleep_sec)
dt_no_cache = Time.now-t
expect(dt_no_cache).to be > sleep_sec
t = Time.now
OpenUriCache.open(url, cache_dir: tmpdir, sleep_sec: sleep_sec)
dt_cache = Time.now-t
expect(dt_cache).to be < sleep_sec # may be almost 0
}
end
it 'success check' do
Dir.mktmpdir {|tmpdir|
url = 'https://twitter.com'
t = Time.now
expect {
OpenUriCache.open(url, cache_dir: tmpdir, success_check: lambda {|f| false })
}.to raise_error(OpenUriCache::SuccessCheckError)
OpenUriCache.open(url, cache_dir: tmpdir, success_check: lambda {|f| f.content_type.match('text/html') })
}
end
it 'retry' do
Dir.mktmpdir {|tmpdir|
url = 'https://twitter.com'
OpenUriCache.open(url, cache_dir: tmpdir, retry_num: 3)
url = 'htps://twitter.com'
t = Time.now
n = 3
s = 0.25
expect {
OpenUriCache.open(url, cache_dir: tmpdir, retry_num: n, sleep_sec: s)
}.to raise_error
dt = Time.now - t
expect(dt).to be > s*(n+1)
}
end
end
|
mokos/open_uri_cache
|
lib/open_uri_cache.rb
|
require_relative 'open_uri_cache/version'
require 'fileutils'
require 'pathname'
require 'open-uri'
require 'cgi'
require 'json'
module OpenUriCache
class SuccessCheckError < StandardError; end
class CacheFile < File
private_class_method :new
def set_info(info)
@info = info
end
def method_missing(name)
n = name.to_s
if @info.has_key? n
@info[n]
else
super
end
end
def self.open(file_path, info, *args)
f = super(file_path, *args)
f.set_info(info)
f
end
end
class Cache
def initialize(uri, dir)
@uri = uri
@dir = Pathname.new(dir).join(uri.gsub(/^(https?|ftp):\/\//, ''))
@content_path = "#{@dir}/content"
@info_path = "#{@dir}/info.json"
delete_expired_cache
end
def delete_expired_cache
return unless exist?
if Time.now > Time.parse(info_json['expiration'])
delete
end
end
def info_json
JSON.parse File.open(@info_path, 'r') {|f| f.read }
end
def delete
File.delete @content_path
File.delete @info_path
Dir.rmdir @dir rescue nil
end
def exist?
File.exist? @content_path and File.exist? @info_path
end
def save(content, info)
FileUtils.mkdir_p(@dir)
File.open(@content_path, 'wb+') {|f|
f.write content
}
File.open(@info_path, 'w+') {|f|
f.puts info.to_json
}
end
def open(*args)
CacheFile.open(@content_path, info_json, *args)
end
end
DEFAULT_CACHE_DIRECTORY = "#{ENV['HOME']}/.open_uri_cache"
def self.open(uri, *rest, cache_dir: DEFAULT_CACHE_DIRECTORY, expiration: nil, after: nil, sleep_sec: 0, retry_num: 0, success_check: lambda {|f| true })
if after
expiration = Time.now + after
end
expiration ||= Time.new(9999, 1, 1)
cache = Cache.new(uri, cache_dir)
if cache.exist?
return cache.open(*rest)
end
begin
sleep sleep_sec
f = Kernel.open(uri, 'rb')
raise SuccessCheckError unless success_check.call f
rescue
retry_num -= 1
retry if retry_num>=0
raise
end
info = {
expiration: expiration,
base_uri: f.base_uri,
charset: f.charset,
content_encoding: f.content_encoding,
content_type: f.content_type,
last_modified: f.last_modified,
meta: f.meta,
status: f.status,
}
cache.save(f.read, info) rescue cache.delete
f.rewind
return f
end
end
|
pirvudoru/php-serialize
|
lib/php-serialize.rb
|
<reponame>pirvudoru/php-serialize
# Bunlder auto requires the gemname, so we redirect to the right file.
require "php_serialize"
|
whiplashmerch/omniauth-whiplash
|
lib/omniauth/whiplash.rb
|
<filename>lib/omniauth/whiplash.rb
require "omniauth-oauth2"
require "omniauth/whiplash/version"
require "omniauth/strategies/whiplash"
|
whiplashmerch/omniauth-whiplash
|
lib/omniauth/whiplash/version.rb
|
module Omniauth
module Whiplash
VERSION = "0.2.4"
end
end
|
whiplashmerch/omniauth-whiplash
|
lib/omniauth/strategies/whiplash.rb
|
<reponame>whiplashmerch/omniauth-whiplash
module OmniAuth
module Strategies
class Whiplash < OmniAuth::Strategies::OAuth2
option :name, :whiplash
option :client_options, {
site: ENV['WHIPLASH_API_URL'] || "https://www.getwhiplash.com",
authorize_url: "/oauth/authorize"
}
uid { raw_info["id"] }
info do
{
email: raw_info["email"],
first_name: raw_info["first_name"],
last_name: raw_info["last_name"],
role: raw_info["role"],
locale: raw_info["locale"],
partner_id: raw_info["partner_id"],
warehouse_id: raw_info["warehouse_id"],
customer_ids: raw_info["customer_ids"]
}
end
def raw_info
@raw_info ||= access_token.get('/api/v2/me').parsed
end
# https://github.com/intridea/omniauth-oauth2/issues/81
def callback_url
full_host + script_name + callback_path
end
end
end
end
|
seanmcneil/Spitfire
|
Spitfire.podspec
|
Pod::Spec.new do |s|
s.name = 'Spitfire'
s.version = '2.1.1'
s.summary = 'A fairly basic utility for taking an array of UIImages and producing a MOV video file.'
s.description = <<-DESC
Spitfire will take an array of one or more UIImages, and produce a video file from them. It provides a nice range of error messages to assist in troubleshooting, and is designed
such that it should handle most common scenarios without any problems.
DESC
s.author = { "<NAME>" => "<EMAIL>" }
s.homepage = 'https://github.com/seanmcneil/Spitfire'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.source = { :git => 'https://github.com/seanmcneil/Spitfire.git', :tag => s.version.to_s }
s.swift_versions = '5.0'
s.ios.deployment_target = '11.0'
s.source_files = 'Spitfire/Classes/**/*'
end
|
underscorgan/vanagon-test-child
|
configs/components/child.rb
|
<reponame>underscorgan/vanagon-test-child<gh_stars>0
component 'child' do |pkg, settings, platform|
pkg.version '0.0.1'
pkg.url 'http://downloads.puppet.com/puppet-gpg-signing-key.pub'
pkg.md5sum 'e6592bb040215d92f44aaa4547569881'
pkg.install do
'touch /vanagon-child'
end
end
|
underscorgan/vanagon-test-child
|
configs/projects/child.rb
|
project 'child' do |proj|
proj.version '0.0.1'
proj.component 'child'
proj.description 'this is a test project'
proj.vendor 'morgan <<EMAIL>>'
proj.license 'Apache-2.0'
proj.homepage 'http://example.com'
end
|
videlanicolas/puppet-ceph
|
spec/acceptance/ceph_mon_osd_spec.rb
|
<reponame>videlanicolas/puppet-ceph
#
# Copyright (C) 2015 <NAME>
#
# Author: <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper_acceptance'
describe 'ceph mon osd' do
context 'default parameters' do
it 'should install one monitor and one OSD on /srv/data' do
pp = <<-EOS
class { 'ceph::repo':
enable_sig => true,
enable_epel => false,
ceph_mirror => $ceph_mirror,
}
class { 'ceph':
fsid => '82274746-9a2c-426b-8c51-107fb0d890c6',
mon_host => $::ipaddress,
authentication_type => 'none',
osd_pool_default_size => '1',
osd_pool_default_min_size => '1',
osd_max_object_namespace_len => '64',
osd_max_object_name_len => '256',
}
ceph_config {
'global/osd_journal_size': value => '100';
}
ceph::mgr { 'a':
authentication_type => 'none',
}
ceph::mon { 'a':
public_addr => $::ipaddress,
authentication_type => 'none',
}
ceph::osd { '/srv/data': }
EOS
apply_manifest(pp, :catch_failures => true)
apply_manifest(pp, :catch_changes => true)
if os[:family].casecmp('RedHat') == 0
describe command('sleep 10') do
its(:exit_status) { should eq 0 }
end
describe command('ceph -s') do
its(:exit_status) { should eq 0 }
its(:stdout) { should match /mon: 1 daemons/) }
its(:stderr) { should be_empty }
end
describe command('ceph osd tree | grep osd.0') do
its(:exit_status) { should eq 0 }
its(:stdout) { should match /up/ }
its(:stderr) { should be_empty }
end
end
end
end
|
videlanicolas/puppet-ceph
|
spec/defines/ceph_rbd_mirror_spec.rb
|
# Copyright (C) 2016 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: <NAME> <<EMAIL>>
#
require 'spec_helper'
describe 'ceph::mirror' do
shared_examples 'ceph::mirror on Debian' do
before do
facts.merge!( :operatingsystem => 'Ubuntu',
:operatingsystemrelease => '16.04',
:service_provider => 'systemd' )
end
context 'with default params' do
let :title do
'A'
end
it { should contain_service('ceph-rbd-mirror@A').with('ensure' => 'running') }
end
end
shared_examples 'ceph::mirror on RedHat' do
before do
facts.merge!( :operatingsystem => 'RedHat',
:operatingsystemrelease => '7.2',
:operatingsystemmajrelease => '7',
:service_provider => 'systemd' )
end
context 'with default params' do
let :title do
'A'
end
it { should contain_service('ceph-rbd-mirror@A').with('ensure' => 'running') }
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge!(OSDefaults.get_facts())
end
it_behaves_like "ceph::mirror on #{facts[:osfamily]}"
end
end
end
|
videlanicolas/puppet-ceph
|
spec/classes/ceph_conf_spec.rb
|
<gh_stars>10-100
#
# Copyright (C) 2013 Cloudwatt <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: <NAME> <<EMAIL>>
#
require 'spec_helper'
describe 'ceph::conf' do
let :params do
{
:args => {
'A' => {
'value' => 'AA VALUE',
},
'B' => { }
},
:defaults => {
'value' => 'DEFAULT',
},
}
end
shared_examples 'ceph::conf' do
context 'with specified parameters' do
it {
should contain_ceph_config('A').with_value('AA VALUE')
should contain_ceph_config('B').with_value('DEFAULT')
}
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge!(OSDefaults.get_facts())
end
it_behaves_like 'ceph::conf'
end
end
end
|
videlanicolas/puppet-ceph
|
spec/defines/ceph_pool_spec.rb
|
#
# Copyright (C) 2014 Catalyst IT Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: <NAME> <<EMAIL>>
#
require 'spec_helper'
describe 'ceph::pool' do
shared_examples 'ceph pool' do
describe "create with custom params" do
let :title do
'volumes'
end
let :params do
{
:ensure => 'present',
:pg_num => 3,
:pgp_num => 4,
:size => 2,
:tag => 'rbd',
}
end
it {
should contain_exec('create-volumes').with(
'command' => "/bin/true # comment to satisfy puppet syntax requirements\nset -ex\nceph osd pool create volumes 3"
)
should contain_exec('set-volumes-pg_num').with(
'command' => "/bin/true # comment to satisfy puppet syntax requirements\nset -ex\nceph osd pool set volumes pg_num 3"
)
should contain_exec('set-volumes-pgp_num').with(
'command' => "/bin/true # comment to satisfy puppet syntax requirements\nset -ex\nceph osd pool set volumes pgp_num 4"
).that_requires('Exec[set-volumes-pg_num]')
should contain_exec('set-volumes-size').with(
'command' => "/bin/true # comment to satisfy puppet syntax requirements\nset -ex\nceph osd pool set volumes size 2"
)
should contain_exec('set-volumes-tag').with(
'command' => "/bin/true # comment to satisfy puppet syntax requirements\nset -ex\nceph osd pool application enable volumes rbd"
)
should_not contain_exec('delete-volumes')
}
end
describe "delete with custom params" do
let :title do
'volumes'
end
let :params do
{
:ensure => 'absent',
}
end
it {
should_not contain_exec('create-volumes')
should contain_exec('delete-volumes').with(
'command' => "/bin/true # comment to satisfy puppet syntax requirements\nset -ex\nceph osd pool delete volumes volumes --yes-i-really-really-mean-it"
)
}
end
end
on_supported_os({
:supported_os => OSDefaults.get_supported_os
}).each do |os,facts|
context "on #{os}" do
let (:facts) do
facts.merge!(OSDefaults.get_facts())
end
it_behaves_like 'ceph pool'
end
end
end
|
videlanicolas/puppet-ceph
|
spec/classes/ceph_profile_base_spec.rb
|
#
# Copyright (C) 2014 Nine Internet Solutions AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: <NAME> <<EMAIL>>
#
require 'spec_helper'
describe 'ceph::profile::base' do
shared_examples 'ceph profile base' do
describe "with default params" do
it { should contain_class('ceph::profile::params') }
it { should contain_class('ceph::repo') }
it { should contain_class('ceph') }
end
describe "with custom param manage_repo false" do
let :pre_condition do
"class { 'ceph::profile::params': manage_repo => false }"
end
it { should contain_class('ceph::profile::params') }
it { should_not contain_class('ceph::repo') }
it { should contain_class('ceph') }
end
end
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge({})
end
it_behaves_like 'ceph profile base'
end
end
end
|
videlanicolas/puppet-ceph
|
lib/puppet/type/ceph_config.rb
|
<reponame>videlanicolas/puppet-ceph<gh_stars>1-10
# Copyright (C) <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: <NAME> <<EMAIL>>
# Author: <NAME> <mgagne>
Puppet::Type.newtype(:ceph_config) do
ensurable
newparam(:name, :namevar => true) do
desc 'Section/setting name to manage from ./ceph.conf'
newvalues(/\S+\/\S+/)
end
# required in order to be able to unit test file contents
# Note: purge will not work on over-ridden file_path
# lifted from ini_file
newparam(:path) do
desc 'A file path to over ride the default file path if necessary'
validate do |value|
unless (Puppet.features.posix? and value =~ /^\//) or (Puppet.features.microsoft_windows? and (value =~ /^.:\// or value =~ /^\/\/[^\/]+\/[^\/]+/))
raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'")
end
end
defaultto false
end
newproperty(:value) do
desc 'The value of the setting to be defined.'
munge do |value|
value = value.to_s.strip
value.downcase! if value =~ /^(true|false)$/i
value
end
end
end
|
videlanicolas/puppet-ceph
|
spec/unit/provider/ceph_config/ini_setting_spec.rb
|
<reponame>videlanicolas/puppet-ceph
# Copyright (C) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: <NAME> <xarses>
# This is aparently one of the few ways to do this load
# see https://github.com/openstack/puppet-nova/blob/master/spec/unit/provider/nova_config/ini_setting_spec.rb
$LOAD_PATH.push(
File.join(
File.dirname(__FILE__),
'..',
'..',
'..',
'fixtures',
'modules',
'inifile',
'lib')
)
require 'spec_helper'
require 'puppet'
provider_class = Puppet::Type.type(:ceph_config).provider(:ini_setting)
describe provider_class do
include PuppetlabsSpec::Files
let(:tmpfile) { tmpfilename("ceph_config_test") }
let(:params) { {
:path => tmpfile,
} }
def validate(expected)
expect(File.read(tmpfile)).to eq(expected)
end
it 'should create keys = value and ensure space around equals' do
resource = Puppet::Type::Ceph_config.new(params.merge(
:name => 'global/ceph_is_foo', :value => 'bar'))
provider = provider_class.new(resource)
expect(provider.exists?).to be_falsey
provider.create
expect(provider.exists?).to be_truthy
validate(<<-EOS
[global]
ceph_is_foo = bar
EOS
)
end
it 'should default to file_path if param path is not passed' do
resource = Puppet::Type::Ceph_config.new(
:name => 'global/ceph_is_foo', :value => 'bar')
provider = provider_class.new(resource)
expect(provider.file_path).to eq('/etc/ceph/ceph.conf')
end
end
|
videlanicolas/puppet-ceph
|
spec/spec_helper.rb
|
# Load libraries from openstacklib here to simulate how they live together in a real puppet run (for provider unit tests)
$LOAD_PATH.push(File.join(File.dirname(__FILE__), 'fixtures', 'modules', 'openstacklib', 'lib'))
require 'puppetlabs_spec_helper/module_spec_helper'
require 'shared_examples'
require 'puppet-openstack_spec_helper/facts'
fixture_path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures'))
RSpec.configure do |c|
c.alias_it_should_behave_like_to :it_configures, 'configures'
c.alias_it_should_behave_like_to :it_raises, 'raises'
c.hiera_config = File.join(fixture_path, 'hieradata/hiera.yaml')
c.module_path = File.join(fixture_path, 'modules')
c.manifest_dir = File.join(fixture_path, 'manifests')
c.before(:all) do
data = YAML.load_file(c.hiera_config)
data[:yaml][:datadir] = File.join(fixture_path, 'hieradata')
File.open(c.hiera_config, 'w') do |f|
f.write data.to_yaml
end
end
c.after(:all) do
`git checkout -- #{c.hiera_config}`
end
end
at_exit { RSpec::Puppet::Coverage.report! }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.