text stringlengths 10 2.61M |
|---|
require 'pry'
class CashRegister
attr_accessor :total, :discount, :cart
def initialize(discount=0)
@total = 0
@discount = discount
@cart = []
end
def add_item(title, price, quantity=1)
cart_hash = {}
cart_hash[:item] = title
cart_hash[:price]... |
require './cellnum'
require 'pp'
require './disassembler.rb'
class CoreThread
attr_accessor :player
attr_accessor :eip,:iret,:r1,:r2,:acc,:ptr
attr_accessor :interrupt_enable,:Imem,:Icza,:Iclk #interrupt flags
attr_accessor :Tmem,:Tcza,:Tclk #interrupt vector target addresses
attr... |
require 'hashie'
module Traject
module Hashie
# Backporting fix from https://github.com/intridea/hashie/commit/a82c594710e1bc9460d3de4d2989cb700f4c3c7f
# into Hashie.
#
# This makes merge(ordinary_hash) on a Hash that has IndifferentAccess included work, without
# raising. Which we needed.
#
... |
require 'rack/livereload'
require 'middleman-livereload/reactor'
module Middleman
module LiveReload
class << self
@@reactor = nil
def registered(app, options={})
options = {
:api_version => '1.6',
:host => '0.0.0.0',
:port => '35729',
:apply_js_live =>... |
require 'rails_helper'
describe PurchasesController, type: :controller do
describe 'GET #new' do
it "renders the :new template" do
category = create(:category)
user = create(:user)
address = create(:address, user: user)
sign_in(user)
item = create(:item, user: user, category: categ... |
require 'spec_helper'
require 'webpay/mock'
describe Spree::PaymentMethod::Webpay do
subject(:payment_method) { described_class.new() }
before do
payment_method.preferences = { secret_key: 'test_secret_xxx' }
end
let(:empty_avs_result) { {"code" => nil, "message" => nil, "street_match" => nil, "postal_matc... |
class Interest < ApplicationRecord
has_many :user_interests
has_many :users, through: :user_interests
validates :name, presence: true, blank: false
end
|
class MedicationsController < ApplicationController
def index
@medications = current_user.medications
end
def show
@medication = current_user.medications
end
def new
@medication = Medication.new
end
def edit
@medication = Medication.find(params[:id])
end
def create
@medication = ... |
# TODO Lifted from Rails master, once this is released switch to the ActiveRecord version
module SecureToken
extend ActiveSupport::Concern
module ClassMethods
# Example using has_secure_token
#
# # Schema: User(token:string, auth_token:string)
# class User < ActiveRecord::Base
# has_sec... |
class ChangeGroupEnabledDefaultToFalse < ActiveRecord::Migration[5.2]
def up
change_column :groups, :enabled, :boolean, default: false
end
def down
change_column :groups, :enabled, :boolean, default: true
end
end
|
require_relative 'base'
class BaseReddit < Base
attr_accessor :reddit_object
def get_from_reddit(klass, existing_list, ended_at, after, limit, count)
args = { limit: limit, count: count }
if(after)
args[:after] = after
end
list = klass.reddit_accessor(reddit_object, args)
if (list.length... |
# discussion posts attached to an event
# although admins may not post directly on an event page,
# admin announcements also create new Post objects
class Post < ActiveRecord::Base
belongs_to :event, class_name: "Event"
belongs_to :user
default_scope -> {order('created_at DESC')}
validates :content, presence:... |
module Crawlers
module Carrefour
class RegistrationCrawler < Crawlers::ApplicationCrawler
CARREFOUR_BASE_URL = 'https://www.carrefour.com.br'.freeze
CARREFOUR_HOME_URL = 'https://www.carrefour.com.br/dicas/mercado'.freeze
CARREFOUR_MODEL = Market.find_by(name: 'Carrefour')
class << self
... |
require 'rss/2.0'
require 'open-uri'
class HomeController < ApplicationController
before_filter :set_blog_news_count
def set_blog_news_count
@blogNewsCount = 12
end
def title
"Fly Fishing"
end
class BlogNews
attr_reader :title, :link, :description, :image_link
d... |
class ColorTest < Test
def setup
@class = Color
@object = @class[0, 0, 0]
end
def test_implements_color_interface
assert_respond_to(@class, :[])
%i[value == to_s to_hex].each do |method|
assert_respond_to(@object, method)
end
end
def test_initializes_with_bytes
assert_equal([2... |
module IsoDoc
module Gb
# A {Converter} implementation that generates GB output, and a document
# schema encapsulation of the document for validation
class HtmlConvert < IsoDoc::HtmlConvert
def formula_parse(node, out)
out.div **attr_code(id: node["id"], class: "formula") do |div|
... |
# Write your code here.
katz_deli = []
# 1. Build the `line` method that shows everyone their current place in the line. If there is nobody in line, it should say `"The line is currently empty."`.
def line(queue)
deli_line = "The line is currently:"
if queue.size == 0
puts "The line is currently empty... |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'RailsAdmin Devise Authentication', type: :request do
subject { page }
let!(:user) { FactoryBot.create :user }
before do
RailsAdmin.config do |config|
config.authenticate_with do
warden.authenticate! scope: :user
end
... |
require "completeness/version"
require "active_support/concern"
require "active_support/core_ext/object/blank"
require "active_support/core_ext/object/try"
require "active_support/core_ext/class"
# Helps calculate the percent of populated fields of the object
# ==== Examples
# class Profile
# attr_accessor :add... |
require 'rails_helper'
RSpec.describe Admin::SponsorsController, :type => :controller do
let(:admin) { create :user }
before { sign_in admin }
describe 'index' do
it 'returns http success' do
get :index
expect(response).to be_success
assigns(:sponsors)
end
end
describe 'new' do
... |
class Admin::ClientsController < ApplicationController
before_action :require_admin_user
layout "admin/admin"
def index
@clients = Client.all
end
def new
@client = Client.new
end
end
|
require 'rails_helper'
RSpec.describe "home/index.html.erb", :type => :view do
it 'display home page correctly' do
render
rendered.expect have_selector('h1', text: 'Home#index')
end
end
|
require 'spec_helper'
describe PaymentDetailsController do
after(:all) do
User.delete_all
end
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
FactoryGirl.create(:configuration_setting)
@user = FactoryGirl.create(:user, payment_method: true, confirmed_at: "2013-05-28... |
# require 'csv'
# puts 'EventManager Initialized!'
## How to open a file
# contents = File.read('event_attendees.csv')
# puts contents
## How to load a file
# lines = File.readlines('event_attendees.csv')
# lines.each_with_index do |line, index|
# next if index == 0
# columns = line.split(',')
# name = column... |
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel_#{params[:room]}"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def move(data)
ActionCable.server.broadcast("room_channel_#{data['room']}", id: data['id'])
end
end
|
class FavoriteLocation
def initialize(locations)
@locations = locations
end
def location_hash
@locations
end
end
|
# Helper Method
def position_taken?(board, location)
!(board[location].nil? || board[location] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
# top row win
[0, 1, 2],
# middle row win
[3, 4, 5],
# bottom row win
[6, 7, 8],
# vertical l... |
# A single checkpoint on the map
class Checkpoint
attr_reader :trigger_shape
def self.new_with(map:, space:)
static_body = CP::StaticBody.new
checkpoints = map['checkpoints'].map do |(start, finish)|
Checkpoint.new(
from: start, to: finish, static_body: static_body, tilesize: map['tilesize']
... |
# encoding: utf-8
control "V-53987" do
title "Oracle roles granted using the WITH ADMIN OPTION must not be granted to unauthorized accounts."
desc "The WITH ADMIN OPTION allows the grantee to grant a role to another database account. Best security practice restricts the privilege of assigning privileges to authorize... |
require 'test_helper'
class UploadsPage < ActionDispatch::IntegrationTest
setup do
SignInRick.call(self);
@project = Project.unscoped.where(name: "Police Station").first
end
test "list all uploads for project" do
visit "/projects/#{@project.id}/uploads"
Upload.unscoped.where(project: @project).... |
require 'rubygems'
require 'bundler/setup'
require 'grape'
require 'grape/apidoc'
class TestAPI < Grape::API
default_format :json
desc "say hello"
params do
requires :name, type: String, desc: "Your name"
optional :a_number, type: Integer, desc: "A number"
end
get do
{:message => "Hel... |
class AddBeginendToTarea < ActiveRecord::Migration[5.0]
def change
add_column :tareas, :begin_time, :datetime
add_column :tareas, :end_time, :datetime
end
end
|
class Sysadmin::UsersController < Sysadmin::BaseController
# load_and_authorize_resource
helper_method :sort_column, :sort_direction
set_tab :users
def index
@users = User.sysadmins.exclude_users([current_user.id]).order(sort_column + " " + sort_direction).page(params[:page]).per(10)
respond_to do |... |
require 'eb_ruby_client/connection'
RSpec.describe EbRubyClient::Connection do
let(:base_url) { "http://some.url/" }
let(:token) { "http://some.url/" }
let(:configuration) { double(:configuration, base_url: base_url, auth_token: token)}
let(:path) { "some/path" }
let(:full_path) { "#{base_url}/#{path}"}
... |
# GSPlan - Team commitment planning
#
# Copyright (C) 2008 Jan Schrage <jan@jschrage.de>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the License,
# or (at your option) ... |
class Post < ActiveRecord::Base
belongs_to :user
has_many :categorizations, :dependent => :destroy
has_many :categories, through: :categorizations
end
|
#
# network_interfaces.rb - A simple wrapper class for ifconfig.rb
#
# Usage:
#
# NetworkInterfaces.each do | each |
# p each.ip_address
# p each.subnet
# p each.netmask
# ...
# end
#
require 'ifconfig'
class NetworkInterfaces
ifconfig = IfconfigWrapper.new.parse
@@interfaces = ifconfig.in... |
module DiningPhilosophers
module V1
class Philosopher
def initialize(name)
@name = name
end
def dine(table, position)
@left_chopstick = table.left_chopstick_at(position)
@right_chopstick = table.right_chopstick_at(position)
loop do
think
eat... |
# encoding: utf-8
control "V-53985" do
title "System Privileges must not be granted to PUBLIC."
desc "System privileges can be granted to users and roles and to the user group PUBLIC. All privileges granted to PUBLIC are accessible to every user in the database. Many of these privileges convey considerable authority... |
RSpec.shared_examples 'Neo4j::Label' do
before(:all) do
r = Random.new
@label1 = ('R1 ' + r.rand(0..1_000_000).to_s).to_sym
@label2 = ('R2 ' + r.rand(0..1_000_000).to_s).to_sym
@random_label = ('R3 ' + r.rand(0..1_000_000).to_s).to_sym
@red1 = Neo4j::Node.create({}, @label1)
@red2 = Neo4j::Nod... |
class RegisteredApplicationsController < ApplicationController
def index
@applications = RegisteredApplication.all
end
def show
@application = RegisteredApplication.find(params[:id])
@event_groups = @application.events.group_by(&:name)
end
def new
@application = RegisteredApplication.new(... |
Rails.application.routes.draw do
resources :users, only: [:new, :create]
resources :blogs, only: [:new, :create, :index]
resources :sessions, only: [:new, :create]
root to: "blogs#index"
end
|
# frozen_string_literal: true
require 'json'
EXTRACT_DEPENDENCY_NAME = /"?(.+?)@.+?"?(?:,\s+|\Z)/.freeze
EXTRACT_DEPENDENCY_DETAILS = /(^((?!= ).*?):\n.*?(?:\n\n|\Z))/m.freeze
def direct_dependencies_names
package_json = JSON.parse(File.open('package.json').read)
direct_dependencies = package_json.fetch_values('... |
object @inscription
node :errors do |m|
m.errors.full_messages
end
|
class CreateMotivationalMessages < ActiveRecord::Migration
def change
create_table :motivational_messages do |t|
t.integer :month
t.text :english
t.timestamps
end
end
end
|
class IngredientNamesProductTag < ActiveRecord::Base
belongs_to :ingredient_name
belongs_to :product_tag
end |
class FakeArray
attr_reader :args
# you'll need a splat in this class somewhere
def initialize(*args)
@args = args
end
def [](num)
@args[num]
end
def each
@args.each do |x|
yield x
end
end
def first
@args[0]
end
end
|
class Ride < ApplicationRecord
belongs_to :cab
attr_accessor :pink
PER_KM = 2
PINK_CHARGE = 5
#validations
validates :source_latitude, :source_longitude, presence: true
validates :cab, presence: true
validates :destination_latitude, presence: true
validates :destination_longitude, presence: true
... |
class Goal < ApplicationRecord
belongs_to :user
before_save :set_defaults
private
def set_defaults
if self.new_record?
self.remaining = self.target
self.default = true if self.user.goals.count == 0
end
end
end
|
class KeventerEventType
attr_accessor :id, :name, :subtitle, :goal, :description, :recipients, :program, :duration, :faqs,
:elevator_pitch, :learnings, :takeaways, :elevator_pitch, :include_in_catalog,
:public_editions, :average_rating, :net_promoter_score, :surveyed_count,
... |
class LocationsController < ApplicationController
def new
@location = Location.new
end
def create
@location = Location.new
if @location.save
redirect_to root_path, notice: "new location!"
else
render :new
end
end
def show
@locations = Location.order(:name)
@location = ... |
module Setup
class Snippet
include Mongoid::Document
include CrossOrigin::Document
include Cenit::MultiTenancy::Scoped
origins :default, -> { Cenit::MultiTenancy.tenant_model.current && :owner }, :shared
field :code, type: String, default: ''
end
end
|
require "aws/s3"
class Array
def export_csv(filename)
csv_string = ""
self.each do |e|
csv_string << e.to_csv
end
config = YAML.load(File.open("#{Rails.root}/config/s3.yml"))[Rails.env]
s3 = AWS::S3.new
bucket = s3.buckets[config['bucket']]
bucket.objects[filename].write(csv_string)
... |
class TasksController < ApplicationController
before_action :load_subject, only: :create
def create
@task = @subject.tasks.build task_params
if @task.save
load_tasks
respond_to :js
else
flash[:danger] = t "controllers.tasks.create_task_success"
redirect_to subject_path(@subject)... |
require 'aws-sdk'
require 'deploy/aws/utils'
require 'pp'
class LambdaAws
DOES_NOT_EXIST = nil
include Lambda
include InternalUtils
def initialize(options)
@verbose = options.verbose
@verbose2 = options.verbose2
@creds = load_creds(options.credentials)
@client = Aws::Lambda::Client.new(
... |
class OrderSerializer < ActiveModel::Serializer
attributes :id
has_many :order_items
has_many :products, through: :order_items
end
|
class Index::PostHistory < ApplicationRecord
belongs_to :user,
class_name: 'Index::User',
foreign_key: :user_id,
optional: true
belongs_to :post, -> { with_all },
class_name: 'Index::Post',
foreign_key: :post_id
default_scope { order(update... |
require 'test_helper'
class Finance::ChargingInvoiceStatesTest < ActionDispatch::IntegrationTest
context 'when unpaid' do
setup do
@invoice = FactoryBot.create(:invoice,
:period => Month.new(Time.zone.local(1984, 1, 1)))
@invoice.stubs(:cost).returns(100.to_has_mone... |
# frozen_string_literal: true
require 'test_helper'
class HousePresenterTest < ActiveSupport::TestCase
test 'statuses returns an array of statuses' do
house = StubHouse.new
statuses = HousePresenter.new(house, nil).statuses
assert_equal Array, statuses.class
err_msg = 'House did not return a list of... |
class PagesController < ApplicationController
before_action :store_location, only: :cart
def home
@valid_offers = Offer.valid_offers.order(collect_starts_at: :asc)
@finished_offers = Offer.finished_offers.order(collect_starts_at: :desc).limit(6)
end
def about
end
def cart
end
def terms
... |
module Ahoy
module Views
module Viewer
extend ActiveSupport::Concern
module ClassMethods
def ahoy_viewer
has_many :ahoy_visits, as: :visitor, class_name: 'Ahoy::Event'
has_many :ahoy_viewed, through: :ahoy_visits, source: :vi... |
require 'spec_helper'
describe VCAP::MongodbController::MongoClusterBuilder do
def create_config(params)
VCAP::MongodbController::Config.new({
message_bus_uris: ["some_uri"],
pid_filename: "some file",
... |
class AddSalesDateToComparisonItems < ActiveRecord::Migration[5.2]
def change
add_column :comparison_items, :sales_date, :string
end
end
|
require 'spec_helper'
describe Player do
context "#initialize" do
it { expect{Player.new()}.to raise_error ArgumentError }
player = Player.new( {:name => "Andrew", :mark=> "o"} )
it { expect( player.name ).to eq "Andrew"}
it { expect( player.mark ).to eq "o"}
... |
# encoding: utf-8
module ActiveAdmin
module Views
class IndexAsGallery < ActiveAdmin::Component
def build(page_presenter, collection)
@page_presenter = page_presenter
@collection = collection
@resource_name = active_admin_config.resource_name.to_s.underscore.parameterize('_')
... |
# == Schema Information
#
# Table name: seller_types
#
# id :integer not null, primary key
# name :string(255) not null
# auction_id :integer not null
# created_at :datetime
# updated_at :datetime
# packercalc :string(6) default("NOCALC")
# buyercalc :string(6) ... |
require_relative "spec_helper"
require 'delegate'
describe "Sequel::Plugins::DefaultsSetter" do
before do
@db = db = Sequel.mock
def db.supports_schema_parsing?() true end
def db.schema(*) [] end
db.singleton_class.send(:alias_method, :schema, :schema)
@c = c = Class.new(Sequel::Model(db[:foo]))... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = users(:lana)
end
test "associated posts should be destroyed" do
@user.posts.create!(content: "Lorem ipsum")
assert_difference 'Post.count', -1 do
@user.destroy
end
end
end
|
class Admin::ClassTemplateClassTypesController < Admin::ControllerBase
before_action :find_class_template_class_type, only: :destroy
def create
class_template_class_type = ClassTemplateClassType.create create_params
if class_template_class_type.persisted?
flash[:success] = "Class template linked to c... |
class ImportController < ApplicationController
before_action :authenticate_user!
before_action :set_account
before_action :ensure_account_is_mine
before_action :set_season
def index
@matches = nil
@match_count = @account.matches.in_season(@season_number).count
end
def create
file = params[:c... |
class User < ApplicationRecord
enum sex: {male: 1, female: 2, trans: 3}
has_many :bills
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, format: {with: VALID_EMAIL_REGEX}, presence: true,
uniqueness: {case_sensitive: false},
length: {maximum: Settings.users.email.max_length}
... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'i18n_accessors/version'
Gem::Specification.new do |spec|
spec.name = "i18n_accessors"
spec.version = I18nAccessors::VERSION
spec.authors = ["Chris Salzberg"]
spec.ema... |
require 'rails_helper'
RSpec.describe Batch, type: :model do
it 'can be created without attributes' do
batch = Batch.new
expect(batch).to be_valid
end
describe '#status' do
it 'defaults to "new"' do
batch = Batch.new
expect(batch.status).to eq Batch.NEW
end
it 'can be changed to... |
class AddFieldsToOrders < ActiveRecord::Migration[5.0]
def change
add_column :orders, :product, :string
add_column :orders, :customer_id, :string
end
end
|
require_relative '../test_helper'
class MetadataTest < ActiveSupport::TestCase
test "should create metadata" do
pm = create_project_media
u = create_user
assert_difference "Annotation.where(annotation_type: 'metadata').count" do
create_metadata(annotated: pm, annotator: u)
end
end
test "sh... |
# frozen_string_literal: true
require 'rails_helper'
require 'shared_examples_for_controllers'
RSpec.describe ReservationsController, type: :request do
let(:role) { create(:user_role) }
let(:user) { create(:user, user_role: role) }
let(:screening) { create(:screening, movie: movie, cinema_hall: cinema_hall) }
... |
require 'rubygems'
require 'data_mapper'
#DataMapper.setup(:default, 'sqlite:///#{Dir.pwd}/db/user.db')
a = DataMapper.setup(:default, "sqlite:db/user.db")
class User
include DataMapper::Resource
property :id, Serial
property :email, String
property :password, String
property :userclass, String
property ... |
module CDNLib
# A class to wrap+extend an FTP connection, adding CDN-specific functionality
# and convenience methods
class CDN
require 'net/ftp'
def self.connect(host, user=nil, password=nil)
Net::FTP.open(host) do |ftp_conn|
ftp_conn.extend(FTPExtension)
ftp_conn.login ... |
class CreditCard < ActiveRecord::Base
def self.error_message_for_credit_card_owner_invalid
'The name of the credit card owner cannot be longer than 30 characters'
end
def self.error_message_for_invalid_credit_card
'The credit card is invalid'
end
def self.error_message_for_expired_credit_card
'... |
require_dependency "keppler_capsules/application_controller"
module KepplerCapsules
module Admin
# CapsulesController
class CapsulesController < ::Admin::AdminController
layout 'keppler_capsules/admin/layouts/application'
before_action :set_capsule, only: %i[show edit update destroy destroy_valida... |
class SearchController < ApplicationController
skip_before_action :authenticate_request
def index
if params[:keywords].nil? || params[:keywords].blank?
render json: @posts = []
else
@posts = Post.search(params[:keywords])
render json: @posts, status: 200
end... |
Pod::Spec.new do |spec|
spec.name = 'NoodleKit'
spec.version = '0.0.1'
spec.authors = 'Paul Kim'
spec.summary = "Random collection of Cocoa classes and categories, most of which have been featured on my blog: http://www.noodlesoft.com/blog"
spec.homepage = 'https://github.com/MrNood... |
# Takes files in a `data` directory relative to this script with the structure
#
# ```
# data
# ->2019-11
# ->2019-12
# ->2020-01
# ->2020-02
# ->year-month
# ```
#
# Any filenames containing `street` will be appended to `street.csv`
#
# Any filenames containing `outcome` will be appended to `outcome.csv`
... |
Given(/^that I have selected a task and started a time record$/) do
visit "/"
click_button "bigredbutton"
fill_in "task_name", :with=> "New task"
click_button "New task"
@task = Task.last
tr = TimeRecord.last
tr.task.name.should == "New task"
end
When(/^I write a note and save the note$/) do
tr = TimeReco... |
# Customize this file, documentation can be found here:
# https://docs.fastlane.tools/actions/
# All available actions: https://docs.fastlane.tools/actions
# can also be listed using the `fastlane actions` command
# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane... |
class ProductStatsUpdateNamesForRatings < ActiveRecord::Migration
def self.up
rename_column :product_stats, :active_quick_review_count, :active_rating_review_count
end
def self.down
rename_column :product_stats, :active_rating_review_count, :active_quick_review_count
end
end
|
#Brandon Bosso
#Naomi Plasterer
#defines methods to respond to all DSL statement types (e.g., product, activate, packing
#slip and pay would be required for the file in Figure 1)
#these methods cause appropriate rules to be stored in PaymentRules
#require_relative 'paymentRules.rb'
#require_relative 'paymentMain.rb'
... |
require 'nokogiri'
include AttachmentHelper
include PaperclipExtensions
class Post < ActiveRecord::Base
belongs_to :blog
has_many :songs, :dependent => :destroy
has_attachment :image, :s3 => Yetting.s3_enabled, styles: { medium: ['256x256#'], small: ['128x128#'], icon: ['64x64#'] }
validates :url... |
# copied from: http://lucatironi.net/tutorial/2015/08/23/rails_api_authentication_warden/?utm_source=rubyweekly&utm_medium=email
require 'rails_helper'
RSpec.describe SessionsController, type: :controller do
let!(:user) { User.create(email: "user@example.com", password: "password") }
let!(:authentication_token) {... |
class WoundsController < ApplicationController
def show
@wound = Wound.find(params[:id])
@statuses = @wound.statuses
respond_to do |format|
format.html
format.json { render json: @wound.statuses }
end
end
def new
@wound = Wound.new
end
def create
@wound = Wound.new(wound_params.merge(p... |
# -*- coding: utf-8 -*-
require 'set'
Plugin.create :smartthread do
counter = gen_counter 1
@timeline_slugs = Set.new # [Symbol]
# messagesの中で、タイムライン _slug_ に入れるべきものがあれば入れる
# ==== Args
# [timeline] タイムライン
# [messages] 入れるMessageの配列
def scan(i_timeline, messages)
SerialThread.new do
... |
class Role < ApplicationRecord
before_save :save_validate
has_many :users
validates :name, length: { maximum: 30 }, presence: true, uniqueness: true
private
def save_validate
self.name.capitalize!
end
end
|
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
##
# Exploit Title : junction_shell_folders_persistence.rb
# ... |
require 'markdown_to_html'
class PublicPostsController < ApplicationController
def index
@posts = Post.where(:published_at.lte => Time.now)
.desc(:published_at)
.page(params[:page] || 1)
.per(3)
@next_page = (params[:page] || 1).to_i + 1
if request.xhr?
render 'index', layout: ... |
class AddDetailsToAttachedDocuments < ActiveRecord::Migration
def change
add_column :attached_documents, :description, :string, default: ''
add_column :attached_documents, :last_update, :datetime
add_column :attached_documents, :locked, :boolean, default: false
end
end |
# frozen_string_literal: true
module BackgroundNotifiable
extend ActiveSupport::Concern
def report_progress(args)
current = args[:current]
total = args[:total]
records_per_update = (total / 20).clamp(1, 100)
if background_channel && ((current % records_per_update == 0) || (current == 1) || (curren... |
class PizzaShop
include Diametric::Entity
include Diametric::Persistence::Peer
# Use for validations and options in view
def self.quality_options
%w(poor serviceable decent good excellent)
end
attribute :name, String, index: true
attribute :location, Ref, :cardinality => :one
attribute :quality,... |
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class ArticleTest < ActiveSupport::TestCase
def test_teaser_content
article = Article.new :title => 'Testing displayable content',
:teaser => 'Teaser content',
:content => 'Foo Bar 1<... |
json.array!(@devices) do |device|
json.extract! device, :id, :autnum_id, :name, :fqdn, :platform
json.url device_url(device, format: :json)
end
|
require 'rails_helper'
RSpec.describe 'Profile Orders Show', type: :feature do
describe 'As a Registerd User' do
before :each do
@user = create(:user)
@order_1 = create(:order, user_id: @user.id, status: 0)
@item_1 = create(:item)
@item_2 = create(:item)
@order_item_1 = create(:orde... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.