code
stringlengths
1
1.73M
language
stringclasses
1 value
RSpec.configure do |config| config.include Devise::TestHelpers, :type => :controller end
Ruby
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run BuffaloKids::Application
Ruby
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integrati...
Ruby
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', ...
Ruby
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use yo...
Ruby
Sunspot.config.pagination.default_per_page = 24
Ruby
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
Ruby
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attac...
Ruby
# Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters ...
Ruby
# Be sure to restart your server when you modify this file. BuffaloKids::Application.config.session_store :cookie_store, key: '_buffalo_kids_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with...
Ruby
require 'will_paginate/array'
Ruby
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a probl...
Ruby
BuffaloKids::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.ac...
Ruby
BuffaloKids::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the we...
Ruby
BuffaloKids::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the tes...
Ruby
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application BuffaloKids::Application.initialize!
Ruby
require 'rubygems' # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
Ruby
# Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # Example: # # set :output, "/path/to/my/cron_log.log" # # every 2.hours do # command "/usr/bin/some_great_command" # runner "MyModel.some_m...
Ruby
require File.expand_path('../boot', __FILE__) require 'rails/all' if defined?(Bundler) # If you precompile assets before deploying to production, use this line Bundler.require(*Rails.groups(:assets => %w(development test))) # If you want your assets lazily compiled in production, use this line # Bundler.requi...
Ruby
BuffaloKids::Application.routes.draw do get "books/index" => "books#index" post "book_reservations/new/:book_id" => "book_reservations#new" post "book_reservations/delete/:book_reservation_id" => "book_reservations#delete" get "book_reservations/index/:page" => "book_reservations#index" get "book_reserva...
Ruby
module ApplicationHelper end
Ruby
module UserHelper end
Ruby
class BookInstance < ActiveRecord::Base attr_accessible :book_instance_code, :user_id, :book_id, :photo_registration_id, :book_reservation_id belongs_to :book belongs_to :book_reservation validates_presence_of :book_instance_code; validates_uniqueness_of :book_instance_code; end
Ruby
class PhotoRegistration < ActiveRecord::Base attr_accessible :user_id, :finish_date, :quantity, :book_id belongs_to :user belongs_to :book self.per_page = 12 end
Ruby
class Book < ActiveRecord::Base attr_accessible :title, :book_code, :description, :author, :image_url, :release_date, :rating validates_uniqueness_of :title, :book_code validates_presence_of :title, :book_code before_validation :default_image_url ...
Ruby
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable # Setup acc...
Ruby
class BookReservation < ActiveRecord::Base attr_accessible :user_id, :start_date, :due_date, :extention_days, :receive belongs_to :user has_one :book_instance has_one :book, :through => :book_instance self.per_page = 12 def self.timeout book_reservations = BookReservation.all book_reservations.each ...
Ruby
class Notice < ActiveRecord::Base attr_accessible :title, :content, :user_id validates :title, :content, :presence => true belongs_to :user self.per_page = 12 def short_content self.content.truncate(90) end end
Ruby
class BookReservationsController < ApplicationController before_filter :authenticate_user!, :except => [:home] def home @books = Book.paginate(:page => params[:page]) end def new book = Book.find_by_id(params[:book_id]) if current_user.book_reservations.map{ |a| a.book }.include? book #send...
Ruby
class PhotoRegistrationsController < ApplicationController before_filter :authenticate_user!, :except => [:home] def home @books = Book.paginate(:page => params[:page]) end def new book = Book.find_by_id(params[:book_id]) if current_user.photo_registrations.map{ |a| a.book }.include? book #s...
Ruby
class EtcsController < ApplicationController def faq end def contact end def set_en if current_user.nil? session[:lang] = "en" else current_user.locale = "en" current_user.save end redirect_to params[:path] end def set_vi if current_user.nil? session[:lang] =...
Ruby
class BooksController < ApplicationController # phan cua Viet before_filter :authenticate_user! before_filter :authorized_user?, :except => [:show] def authorized_user? redirect_to(root_path) unless current_user && (current_user.librarian? || current_user.admin?) end def index @books = Boo...
Ruby
class ApplicationController < ActionController::Base protect_from_forgery before_filter :set_locale def set_locale if current_user.nil? I18n.locale = session[:lang].nil? ? "en" : session[:lang] else I18n.locale = current_user.locale end end def after_sign_in_path_for(resource_or_scope) case...
Ruby
class SearchesController < ApplicationController before_filter :authenticate_user! def search render "searches/#{params[:type]}" end def book_advance_search case current_user.role when "user" @books = Book.my_search(params).paginate(:page => params[:page], :per_page => 12) if params[:reservation] =...
Ruby
class BookInstancesController < ApplicationController before_filter :authenticate_user!,:authorized_user? def authorized_user? redirect_to(root_path) unless current_user && (current_user.librarian? || current_user.admin?) end def index @book = Book.find(params[:book_id]) if @book.nil? # send er...
Ruby
class NoticesController < ApplicationController before_filter :authenticate_user! # def authorized_user? # redirect_to(root_path) unless current_user && (current_user.librarian? || current_user.admin?) # end def index @notices = Notice.paginate(:page => params[:page]) end def show @notice...
Ruby
class UsersController < ApplicationController before_filter :authenticate_user!,:authorized_user? def authorized_user? redirect_to(root_path) unless current_user && current_user.admin? end def index @users = User.paginate(:page => params[:page]) end def show @user = User.find_by_id(params[:user_id]) end...
Ruby
#!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) BuffaloKids::Application.load_tasks
Ruby
#!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) BuffaloKids::Application.load_tasks
Ruby
source 'https://rubygems.org' gem 'rails', '3.2.8' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' group :development, :test do gem 'mysql2' end # group :production do # gem 'pg' # end gem 'haml', '3.1.7' gem 'devise', '2.1.2' gem 'jquery-rails', '2.1.2' gem 'will_paginat...
Ruby
class DeviseCreateUsers < ActiveRecord::Migration def change create_table(:users) do |t| ## Database authenticatable t.string :email, :null => false, :default => "" t.string :encrypted_password, :null => false, :default => "" ## Recoverable t.string :reset_password_to...
Ruby
class CreateBooks < ActiveRecord::Migration def change create_table :books do |t| t.string :title t.string :book_code t.text :description t.string :author t.string :category t.date :release_date t.string :image_url t.string :rating t.boolean :available ...
Ruby
class CreateNotices < ActiveRecord::Migration def change create_table :notices do |t| t.string :title t.text :content t.integer :user_id t.timestamps end end end
Ruby
class CreatePhotoRegistrations < ActiveRecord::Migration def change create_table :photo_registrations do |t| t.integer :user_id t.integer :book_id t.date :finish_date t.string :quantity t.timestamps end end end
Ruby
class CreateBookReservations < ActiveRecord::Migration def change create_table :book_reservations do |t| t.integer :user_id t.boolean :receive t.date :start_date t.date :due_date t.integer :extention_days t.timestamps end end end
Ruby
class CreateBookInstances < ActiveRecord::Migration def change create_table :book_instances do |t| t.string :book_instance_code t.integer :book_id t.integer :book_reservation_id t.integer :photo_registration_id t.timestamps end end end
Ruby
# encoding: UTF-8 User.delete_all Notice.delete_all Book.delete_all BookInstance.delete_all BookReservation.delete_all PhotoRegistration.delete_all user1 = User.create(:email => "user1@vit.com", :password => "123456", :password_confirmation => "123456", :remember_me => "true", :username => "user1", :role => "user", :...
Ruby
FactoryGirl.define do factory :book do sequence(:title) {|n| "book#{n}" } sequence(:book_code) {|n| "book_code#{n}" } end end
Ruby
FactoryGirl.define do factory :book_instance do sequence(:book_instance_code) {|n| "book_instance_code#{n}" } end end
Ruby
FactoryGirl.define do factory :user do sequence(:email) {|n| "email#{n}@example.com" } sequence(:username) {|n| "username#{n}" } password "123456" password_confirmation "123456" end factory :unconfirmed_user, :parent => :user do confirmation_token "confirmation_token" end fac...
Ruby
FactoryGirl.define do factory :book_reservation do start_date Date.today due_date Date.today + 3 end end
Ruby
FactoryGirl.define do factory :photo_registration do finish_date Date.today + 3 end end
Ruby
FactoryGirl.define do factory :notice do sequence(:title) {|n| "Title#{n}" } sequence(:content) {|n| "Content#{n}" } end end
Ruby
require 'simplecov' SimpleCov.start ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'capybara/rspec' require 'capybara/rails' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[R...
Ruby
RSpec.configure do |config| config.include Devise::TestHelpers, :type => :controller end
Ruby
# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run BuffaloKids::Application
Ruby
ENV["RAILS_ENV"] = "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integrati...
Ruby
require 'rake' ROOT_DIR = File.expand_path('.') SRC_DIR = File.join(ROOT_DIR, 'src') TMP_DIR = File.join(ROOT_DIR, 'tmp') XCODE_PROJECT = File.join(SRC_DIR, 'Visor.xcodeproj') VISOR_BUNDLE = "Visor.bundle" BUILD_DIR = File.join(SRC_DIR, 'build') BUILD_RELEASE_DIR = File.join(TMP_DIR, 'build', 'Release') BUILD_RELEASE_...
Ruby
require 'rubygems' rescue nil $LOAD_PATH.unshift File.join(File.expand_path(__FILE__), "..", "..", "lib") require 'chingu' require 'texplay' include Chingu include Gosu Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file } $game_bgm = nil $game_enemies = [] $game_hazards = [] $game_terra...
Ruby
# ------------------------------------------------------ # Player # The one who granted the control of you # ------------------------------------------------------ class Player < Chingu::GameObject attr_reader :direction, :invincible, :last_x # , :running, :sword attr_accessor :y_flag, :sword, :status, :action...
Ruby
# ------------------------------------------------------ # Miscellaneous things # TODO: separating animations and hazards # ------------------------------------------------------ class Spark < GameObject traits :timer def setup @spark = Chingu::Animation.new( :file => "misc/spark.gif", :size => [15,15]) @...
Ruby
# ------------------------------------------------------ # Weapons # When you need self-defense # ------------------------------------------------------ class Sword < GameObject trait :bounding_box, :scale => [1, 0.25], :debug => false traits :collision_detection, :timer, :velocity attr_reader :damage attr_...
Ruby
# ------------------------------------------------------ # Scenes # What's happening in each blocks? # ------------------------------------------------------ class Scene < GameState traits :viewport, :timer attr_reader :player, :terrain, :area, :backdrop, :hud def initialize super self.input = { :esca...
Ruby
# ------------------------------------------------------ # Items # Collectibles and valueables # ------------------------------------------------------ class Items < GameObject trait :bounding_box, :debug => false traits :collision_detection, :velocity, :timer def setup @image = Image["items/#{self.fi...
Ruby
# ------------------------------------------------------ # Heads-up-display # ------------------------------------------------------ class HUD < Chingu::BasicGameObject attr_reader :gap def initialize(options={}) super @player = options[:player] || parent.player @x = options[:x]; @y = options[:y] #~ ...
Ruby
# ------------------------------------------------------ # Game States # Handles special game state i.e. pause or # transition between blocks # ------------------------------------------------------ class Pause < GameState def initialize(options={}) super self.input = {:space => :unpause} @color = Color...
Ruby
# ------------------------------------------------------ # Enemies # Everything related to things against our hero # written here # ------------------------------------------------------ class Enemy < GameObject traits :collision_detection, :effect, :velocity, :timer attr_reader :invincible, :hp, :damage, :har...
Ruby
# ------------------------------------------------------ # Modules # modules needed for the game # ------------------------------------------------------ module Module_Game module Environment GRAV_CAP = 8 GRAV_ACC = 0.4 GRAV_WHEN_LAND = 1 end INVULNERABLE_DURATION = 350 BGM =[ #~ "silence...
Ruby
# ------------------------------------------------------ # Terrains # When you need place to place your foot # Also there's decorations and bridges # ------------------------------------------------------ class Block < GameObject trait :bounding_box, :scale => [1,0.9], :debug => false trait :collision_dete...
Ruby
# ------------------------------------------------------ # Maps # A simple implementation of block mapping # ------------------------------------------------------ class Map attr_reader :row, :col attr_accessor :map def initialize(options = {}) @row = options[:row] || 0 @col = options[:col]...
Ruby
поиск пользователей по нику в конференциях {command} [сервер_конференций] [ник_пользователя] */{command} conference.jabber.ru mrDude бот начнет поиск пользователя с ником "mrDude" на сервере conference.jabber.ru
Ruby
самообновление {command} (last/branches) */{command} last бот покажет актуальную версию бота */{command} branches бот обновит/добавит содержимое ветки "branches" */{command} бот обновится из ветки "trunk"
Ruby
просмотр списка макро и их хелпов {command} ([хелп/табу] [макро]) */{command} хелп тык бот покажет помощь по маро "тык" (если, конечно, хелп был добавлен) */{command} табу тык бот запретит макро "тык" */{command} табу тык бот снимет запрет на макро "тык" (в случае, если оно запрещено, конечно) */{command} бот ...
Ruby
добавление нового функционала "на лету" {command} (global) ([add] [название_алиаса] [событие] [переменная0/переменная1/и т.д.] [условие0/условие1/и т.д.] [<!--текст первого условия--><!--текст второго условия--><!--и т.д.-->] [флаг0&флаг1/флаг0&флаг1/и т.д.] (command|set|message) (имя_команды|affiliation|role|chat|pri...
Ruby
управление резервными копиями конференции {command} (лист/создать)/([восстановить] [всё/тему/опции/овнеров/админов/мемберов/баны] (время_бекапа))/([скопировать] [конференция]) */{command} создать бот создаст бекап конференции (хранится максимум 3 резервных копии (у темы 6, т.к. бекапы темы создаются автоматически)) ...
Ruby
логи конференций {command} [год] [месяц] [день] [час] */{command} 2012 12 02 06 бот покажет логи текущей конференции с 06 по 07 часов 02.12.2012 (UTC)
Ruby
контроллер логгера конференций {command} (вкл/выкл)/([пароль] (текст)) */{command} бот покажет состояние логгера */{command} выкл бот отключит логгер в текущей конференции */{command} вкл бот включит логгер в текущей конференции */{command} пароль 1234 бот запишет пароль для веб-интерфейса */{command} пароль ...
Ruby
глобальный контроллер логгера {command} (вкл/выкл)/([директория] [путь]) */{command} бот покажет состояние логгера */{command} выкл бот отключит логгер полностью */{command} вкл бот включит логгер */{command} директория /home/xmpp/chatlogs бот установит "/home/xmpp/chatlogs" в качестве корневой директории логг...
Ruby
просмотр содержимого библиотеки {command} ([показать] (названия)/([автор/жанр/серию] [параметры]))/([инфо] [имя_книги])/([читать] ((номер_страницы) [имя_книги])/(далее)) */{command} бот покажет количество книг в библиотеке */{command} показать бот покажет внутренние идентификаторы книг */{command} показать назван...
Ruby
управление библиотекой {command} [[добавить] [имя_книги]/[[файл] [путь_к_fb2]]]/[[править] [идентификатор_книги] [[инфо] [автор/год/жанр/серия/номер/аннотация/ссылка/название] [отчистить/параметры]]/[[страница] [[добавить] [текст]]/[[удалить] [до/только/после] [номер_страницы]]/[[номер_страницы] [текст]]]]/[[удалить] ...
Ruby
показывает/устанавливает (только для овнеров) командный префикс (список: !, @ , #, ., *) {command} (символ/убрать) */{command} покажет текущий префикс */{command} ! бот установит префикс - "!" */{command} убрать бот будет выполнять команды без префикса
Ruby
устанавливает статус бота в конференции {command} [здесь/везде/адрес_конференции] [занят/ушел/чат/нет] [текст_статуса] */{command} здесь нет ушел спать установит статут "xa" с текстом "ушел спать" в текущей конференции */{command} везде нет ушел спать установит статут во всех конференциях */{command} some_chat@c....
Ruby
бот меняет свой ник на указанный {command} [какой-нибудь_ник] */{command} йаробот бот поменяет ник на "йаробот" в текущей конференции
Ruby
показывает/ставит на бота пароль для входа в конференцию {command} (пароль/нет) */{command} покажет текущий пароль */{command} syzam_otkroisa бот поставит пароль "syzam_otkroisa" во входные настройки, для текущей конференции */{command} нет бот удалит пароль из входных настроек
Ruby
замена jid'а с которого бот будет обслуживать указанную конференцию {command} [jid] (конференция) */{command} some_name@jab.com chat@conference.jab.com бот заменит свой jid в chat@conference.jab.com на some_name@jab.com */{command} some_name@jab.com бот заменит свой jid на some_name@jab.com в текущей конференции
Ruby
Игра "Камень-ножницы-бумага-ящерица-Спок" из ситкома "Теория Большого Взрыва" (The Big Bang Theory) {command} (камень/ножницы/бумага/ящерица/спок) */{command} бот покажет правила */{command} спок собственно игра
Ruby
статистика пользователей чата {command} (nick/jid) */{command} Хазам Алаказам покажет статистику Хазама Алаказама */{command} khazam@j.ru покажет статистику khazam@j.ru */{command} покажет вашу статистику
Ruby
время пребывания юзера в конференции {command} (nick) */{command} Чупакабра покажет время пребывания Чупакабры в конференции */{command} покажет ваше время пребывания в конференции
Ruby
статистика ботлунов {command} [[топ] [глобальный/локальный] (число)]/[[глобальный/локальный] [мой/nick/jid]] */{command} локальный мой покажет вашу статистику в текущей конференции */{command} глобальный мой покажет вашу сводную статистику по всем конференциям в которых сидит бот */{command} топ локальный покаже...
Ruby
выполняет выражение питона {command} ((-l) (-r) (-s)) [code] */{command} delivery("Aaa!!") отправит "Aaa!!" на жид своего верховного админа */{command} -l foo = "bar" бот выполнит выражение, используя локальную область видимости */{command} -r foo = "bar"; result = "Done!" бот выполнит выражение и попытается вер...
Ruby
выполняет shell команду {command} [команда] */{command} TASKLIST /FI "IMAGENAME eq python.exe бот покажет (windows) список запущенных процессов на python и занимаемаю ими память (ram) */{command} ps -o rss -p 12154 покажет (unix) сколько памяти хавает процесс с pid'ом 12154
Ruby
калькулятор {command} [выражение]
Ruby
расчитывает выражение python'а и выдаёт ответ {command} [выражение] */{command} get_file(PidFile) прочитает Pid.txt и покажет его содержимое */{command} ["1", "2"]*3 в ответ получаем -» ['1', '2', '1', '2', '1', '2']
Ruby
планировщик заданий (все даты указаны в UTC) {command} ([тайм-аут] [команда] (параметры))/([цикл] [тайм-аут] [кол-во_циклов] [команда] (параметры))/([дата] [[час]:(минута):(секунда)(&[день].(месяц).(год))] [команда] (параметры))/([стоп] [ID_задания]) */{command} бот покажет все запланированные задания */{command} 6...
Ruby
информация о плагинах бота {command} (плагин) */{command} бот покажет список плагинов */{command} help бот покажет подробную информацию о плагине "help"
Ruby
временное глобальное отключение/включение команд {command} (команда) (вкл/выкл) */{command} бот покажет отключенные команды */{command} трёп бот покажет состояние команды "трёп" */{command} трёп выкл бот отключит команду "трёп" до следующей перезагрузки */{command} трёп вкл обратно подключит команду
Ruby
выгрузка плагинов и функций {command} [плагин] (функция) */{command} talkers бот выгрузит плагин "talkers" */{command} talkers calculate_talkers бот выгрузит функцию подсчёта болтунов (выгрузку функций следует использовать только профи)
Ruby
подгрузка плагинов бота {command} [плагин] */{command} help подгрузи плагин "help"
Ruby
выдача прав постоянного участника {command} [jid/nick] ([/] [причина]) */{command} чувак бот даст чуваку права постоянного участника
Ruby
выпроваживание из конференции {command} [jid/nick] ([/] [причина]) */{command} чувак бот выгонит чувака
Ruby