repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
ambethia/LuckyPrincessNitro
lib/game_helpers.rb
<filename>lib/game_helpers.rb module GameHelpers def load_asset(filename) Gdx.files.internal(RELATIVE_ROOT + "assets/#{filename}") end def lerp(a, b, m = 0.5) (a * (1 - m) + b * m) end def weighted_average(v, w, n = 40) ((v * (n - 1)) + w) / n; end end
ambethia/LuckyPrincessNitro
lib/components/ranged_cull_component.rb
class RangedCullComponent < EntitySystem::Component provides :range end
ambethia/LuckyPrincessNitro
test/test_helper.rb
<filename>test/test_helper.rb<gh_stars>1-10 TEST_DIR = File.dirname(__FILE__) LIB_DIR = File.join(TEST_DIR, '..', 'lib') $LOAD_PATH.unshift(TEST_DIR) unless $LOAD_PATH.include?(TEST_DIR) $LOAD_PATH.unshift(LIB_DIR) unless $LOAD_PATH.include?(LIB_DIR) require 'test/unit'
ambethia/LuckyPrincessNitro
lib/screens/victory_screen.rb
class VictoryScreen < BaseScreen def setup @systems = %w[ Input Victory ] end end
ambethia/LuckyPrincessNitro
lib/screens/game_over_screen.rb
class GameOverScreen < BaseScreen def setup @systems = %w[ Input GameOver ] end end
ambethia/LuckyPrincessNitro
lib/systems/victory_system.rb
class VictorySystem < EntitySystem::System def setup @image = Texture.new(Gdx.files.internal(RELATIVE_ROOT + "assets/victory.png")) end def render(delta) if $game.screen.is_a? VictoryScreen $game.screen.batch.draw(@image, 0, 0) end end end
ambethia/LuckyPrincessNitro
config/warble.rb
# Disable Rake-environment-task framework detection by uncommenting/setting to false # Warbler.framework_detection = false # Warbler web application assembly configuration file Warbler::Config.new do |config| config.features = %w(compiled) config.dirs = %w(bin lib vendor) config.includes = FileList["assets/*"] - ["assets/source"] config.jar_name = "Nitro" end
ambethia/LuckyPrincessNitro
lib/systems/animation_system.rb
class AnimationSystem < EntitySystem::System def update(delta) @elapsed ||= 0 each(AnimatedComponent) do |entity, component| render = manager.component(RenderableComponent, entity) render.image = component.animation.get_key_frame(@elapsed, component.is_looped) end @elapsed += delta end end
ambethia/LuckyPrincessNitro
lib/components/enemy_component.rb
class EnemyComponent < EntitySystem::Component provides :type, :data end
ambethia/LuckyPrincessNitro
lib/components/item_component.rb
class ItemComponent < EntitySystem::Component provides :type end
ambethia/LuckyPrincessNitro
lib/components/collision_component.rb
class CollisionComponent < EntitySystem::Component provides :owner, :radius end
ambethia/LuckyPrincessNitro
lib/systems/splash_system.rb
class SplashSystem < EntitySystem::System def setup @image = Texture.new(Gdx.files.internal(RELATIVE_ROOT + "assets/splash.png")) end def render(delta) # For reason I don't want to figure out, this seems to get called # still when were transitioning out of the splash screen and we get # a "SpriteBatch.begin must be called before draw" error. Whatever. if $game.screen.is_a? SplashScreen $game.screen.batch.draw(@image, 0, 0) end end end
ambethia/LuckyPrincessNitro
lib/components/motion_component.rb
class MotionComponent < EntitySystem::Component end
ambethia/LuckyPrincessNitro
lib/systems/particle_system.rb
class ParticleSystem < EntitySystem::System def setup @effects = {} [:explosion, :bullet_destruct, :shield_damage].each do |type| @effects[type] = ParticleEffect.new @effects[type].load_emitters(load_asset("#{type}.particle")) @effects[type].load_emitter_images($game.screen.atlas) end end def update(delta) each(ParticleComponent) do |entity, particle| spatial = manager.component(SpatialComponent, entity) if !particle.started @effects[particle.effect].emitters.each(&:start) particle.started = true end if particle.attach_to target = manager.component(SpatialComponent, particle.attach_to) if target spatial.px = target.px spatial.py = target.py end end @effects[particle.effect].set_position(spatial.px, spatial.py) # TODO: remove finished particle components end end def render(delta) @effects.values.each do |effect| effect.draw($game.screen.batch, delta) end end def reset each(ParticleComponent) do |entity| manager.destroy(entity) end end end
ambethia/LuckyPrincessNitro
lib/components/camera_component.rb
class CameraComponent < EntitySystem::Component provides :object end
ambethia/LuckyPrincessNitro
lib/components/rotated_component.rb
class RotatedComponent < EntitySystem::Component provides :mapping, :is_animated end
ambethia/LuckyPrincessNitro
lib/systems/spawn_system.rb
<filename>lib/systems/spawn_system.rb class SpawnSystem < EntitySystem::System SPAWN_TIME = 1 MAX_ENEMIES = 5 GEM_AREA = 4096 NUM_GEMS = 12 def update(delta) @elapsed ||= 0 @elapsed += delta @active_enemy_count = manager.all(:enemy).size if @active_enemy_count < MAX_ENEMIES if @elapsed > SPAWN_TIME spawn_enemy @elapsed = 0 end else @elapsed = 0 end end def setup atlas = $game.screen.atlas $game.screen.sprites[:gem] = { 0 => atlas.create_sprite("gem", 1), 45 => atlas.create_sprite("gem", 2), 90 => atlas.create_sprite("gem", 3), 135 => atlas.create_sprite("gem", 4), 180 => atlas.create_sprite("gem", 5), 225 => atlas.create_sprite("gem", 6), 270 => atlas.create_sprite("gem", 7), 315 => atlas.create_sprite("gem", 8) } reset end def reset spawn_player($game.width / 2, $game.height / 2) NUM_GEMS.times do spawn_gem( rand(GEM_AREA) - GEM_AREA/2, rand(GEM_AREA) - GEM_AREA/2 ) end end private def spawn_player(x, y) manager.factory.player do |player| player.px = x player.py = y end $game.screen.sounds[:player_spawn].play(2.0) end def spawn_enemy manager.factory.enemy do |enemy| enemy.type = :a end $game.screen.sounds[:enemy_a_spawn].play end def spawn_gem(x, y) manager.factory.item do |item| item.type = :gem item.x = x item.y = y end end end
ambethia/LuckyPrincessNitro
lib/screens/game_screen.rb
<gh_stars>1-10 class GameScreen < BaseScreen def setup @systems = %w[ Input Player Enemy Camera Music RangedCull Collision Spawn Motion Rotation Animation Background Render Particle ] end def debug_text player_id = @entity_manager.find(:player) if player_id player = @entity_manager.component(PlayerComponent, player_id) super + ", Shields: #{player.shields}" else super + ", Player Dead!" end end end
ambethia/LuckyPrincessNitro
lib/entity_system/manager.rb
<reponame>ambethia/LuckyPrincessNitro require 'securerandom' class EntitySystem::Manager UNTAGGED = '' attr_reader :factory def initialize @entities = [] @factory = EntitySystem::Factory.new(self) @ids_to_tags = Hash.new @tags_to_ids = Hash.new @components = Hash.new end def create(tag = UNTAGGED) entity = SecureRandom.uuid @entities << entity @ids_to_tags[entity] = tag if @tags_to_ids.has_key?(tag) @tags_to_ids[tag] << entity else @tags_to_ids[tag] = [entity] end entity end def destroy(entity) @components.each_value do |store| store.delete(entity) end @tags_to_ids.each_key do |tag| if @tags_to_ids[tag].include?(entity) @tags_to_ids[tag].delete(entity) end end @ids_to_tags.delete(entity) @entities.delete(entity) end def attach(entity, component) store = component_store(component.class) component.entity = entity store[entity] = component end def remove(entity, component) store = component_store(component.class) component.entity = nil store[entity] = nil end def component(component_class, entity) component_store(component_class)[entity] end def components(component_class) component_store(component_class).values end def entities(component_class) component_store(component_class).keys end def all(tag) @tags_to_ids[tag] || [] end def find(tag) all(tag).first end def tag(entity) @ids_to_tags[entity] end def size @entities.size end private def component_store(component_class) @components[component_class] ||= Hash.new end end
ambethia/LuckyPrincessNitro
lib/components/renderable_component.rb
class RenderableComponent < EntitySystem::Component provides :image end
ambethia/LuckyPrincessNitro
lib/systems/render_system.rb
class RenderSystem < EntitySystem::System def render(delta) each(RenderableComponent) do |entity, component| image = component.image spatial = manager.component(SpatialComponent, entity) x = spatial.px - image.width/2 y = spatial.py - image.height/2 sprite_batch.draw(image, x, y) end end def sprite_batch @sprite_batch ||= $game.screen.batch end end
ambethia/LuckyPrincessNitro
lib/factories/enemy_factory.rb
<filename>lib/factories/enemy_factory.rb class EnemyFactory < EntitySystem::Factory::Base build :enemy using :type def construct entity = manager.create(:enemy) camera = manager.component(SpatialComponent, manager.find(:camera)) entry_angle = rand(360) manager.attach(entity, EnemyComponent.new({ type: type, data: { c_angle: entry_angle, t_angle: entry_angle, elapsed_since_last_shot: 0, } })) manager.attach(entity, SpatialComponent.new({ px: camera.px + (Math.cos(entry_angle) * ($game.width * 1.2)), py: camera.py + (Math.sin(entry_angle) * ($game.height * 1.2)), bearing: 0, speed: 0 })) manager.attach(entity, RenderableComponent.new) manager.attach(entity, RotatedComponent.new({ mapping: $game.screen.sprites["enemy_#{type}".to_sym] })) end end
ambethia/LuckyPrincessNitro
lib/lucky_princess_nitro.rb
<filename>lib/lucky_princess_nitro.rb require 'game_helpers' require 'entity_system' %w[screens components factories systems].each do |dir| Dir[ROOT_DIR + "/lib/#{dir}/*.rb"].each do |file| require File.basename(file) end end class LuckyPrincessNitro < Game VIRTUAL_WIDTH = 320 VIRTUAL_HEIGHT = 200 DEFAULT_SCALE = 3 include ApplicationListener attr_reader :is_running, :game_screen, :splash_screen, :game_over_screen, :victory_screen, :test_screen def initialize @is_running = true end def create ShaderProgram.pedantic = false @game_screen = GameScreen.new @splash_screen = SplashScreen.new @game_over_screen = GameOverScreen.new @victory_screen = VictoryScreen.new @test_screen = TestScreen.new if ENV['SCREEN'] # for test modes set_screen send("#{ENV['SCREEN']}_screen") else toggle_fullscreen set_screen splash_screen end end def dispose @is_running = false end def toggle_fullscreen mode = Gdx.graphics.get_desktop_display_mode if Gdx.graphics.is_fullscreen Gdx.graphics.set_display_mode(width * DEFAULT_SCALE, height * DEFAULT_SCALE, false) else Gdx.graphics.set_display_mode(mode.width, mode.height, true) end end def game_over set_screen(game_over_screen) end def game_begin set_screen(game_screen) end def game_menu set_screen(splash_screen) end def victory set_screen(victory_screen) end def did_we_win_yet? screen.entity_manager.components(ItemComponent).select { |i| i.type == :gem }.size == 0 end def width VIRTUAL_WIDTH end def height VIRTUAL_HEIGHT end end
ambethia/LuckyPrincessNitro
lib/systems/collision_system.rb
<reponame>ambethia/LuckyPrincessNitro<gh_stars>1-10 class CollisionSystem < EntitySystem::System ENEMY_RADIUS = 8 PLAYER_RADIUS = 8 def update(delta) each(CollisionComponent) do |entity, component| collider_s = manager.component(SpatialComponent, entity) next unless collider_s # incase the collider was suddenly removed collider_c = Circle.new(collider_s.px, collider_s.py, component.radius) player_id = manager.find(:player) case manager.tag(component.owner) when :player # player bullets hitting enemies manager.all(:enemy).each do |enemy| enemy_s = manager.component(SpatialComponent, enemy) enemy_c = Circle.new(enemy_s.px, enemy_s.py, ENEMY_RADIUS) if Intersector.overlapCircles(enemy_c, collider_c) if manager.tag(entity) == :bullet manager.factory.particle do |particle| particle.type = :explosion particle.px = enemy_s.px particle.py = enemy_s.py end $game.screen.sounds[:enemy_a_death].play(0.6) manager.destroy(entity) manager.destroy(enemy) end end end # player bullets hitting enemy bullets manager.all(:bullet).each do |bullet| # dont't destroy our own bullets next if manager.component(CollisionComponent, bullet).owner == player_id bullet_s = manager.component(SpatialComponent, bullet) bullet_c = Circle.new(bullet_s.px, bullet_s.py, component.radius) if Intersector.overlapCircles(bullet_c, collider_c) manager.factory.particle do |particle| particle.type = :bullet_destruct particle.px = bullet_s.px particle.py = bullet_s.py end $game.screen.sounds[:bullet_destruct].play manager.destroy(entity) manager.destroy(bullet) end end when :enemy # enemy bullets hitting the player if player_id player_s = manager.component(SpatialComponent, player_id) player_c = Circle.new(player_s.px, player_s.py, PLAYER_RADIUS) if Intersector.overlapCircles(player_c, collider_c) manager.factory.particle do |particle| particle.type = :shield_damage # TODO: Shield damage particle.attach_to = player_id particle.px = player_s.px particle.py = player_s.py end # sustain damage manager.component(PlayerComponent, player_id).shields -= 1 unless ENV['INVINCIBLE'] $game.screen.sounds[:shield_damage].play manager.destroy(entity) end end when :item # player approaching an item (gem, power up, etc) if player_id player_s = manager.component(SpatialComponent, player_id) player_c = Circle.new(player_s.px, player_s.py, PLAYER_RADIUS) if Intersector.overlapCircles(player_c, collider_c) d = Vector2.new(player_s.px, player_s.py).dst(collider_s.px, collider_s.py) # the gems will gravitate towards the player until they # are close enough to be removed if d > PLAYER_RADIUS * 1.2 p = [(component.radius - d).abs / component.radius, 1].min tx = lerp(collider_s.px, player_s.px, p) ty = lerp(collider_s.py, player_s.py, p) collider_s.px += (tx - collider_s.px) * delta * 14 collider_s.py += (ty - collider_s.py) * delta * 14 # Spin faster approaching the player collider_s.bearing += 15 * d * delta collider_s.bearing %= 360 else # collect the gem $game.screen.sounds[:pickup_gem].play manager.destroy(entity) end end end end end end def reset each(CollisionComponent) do |entity| manager.destroy(entity) end end end
ambethia/LuckyPrincessNitro
lib/components/particle_component.rb
class ParticleComponent < EntitySystem::Component provides :effect, :started, :attach_to end
ambethia/LuckyPrincessNitro
lib/screens/base_screen.rb
class BaseScreen include Screen include GameHelpers attr :atlas, :batch, :sprites, :sounds, :systems, :entity_manager def initialize @sprites = {} @sounds = {} @systems = [] @is_hidden = true setup end def setup end def show unless @is_setup @batch = SpriteBatch.new @atlas = TextureAtlas.new(load_asset("sprites.atlas")) @entity_manager = EntitySystem::Manager.new @interface_system = InterfaceSystem.new(@entity_manager) @initialized_systems = @systems.map { |n| Object.const_get("#{n}System").new(@entity_manager) } @buffer_object = FrameBuffer.new(Pixmap::Format::RGB888, $game.width, $game.height, false) @buffer_texture = @buffer_object.get_color_buffer_texture @buffer_texture.set_filter(Texture::TextureFilter::Nearest, Texture::TextureFilter::Nearest) @buffer_texture_region = TextureRegion.new(@buffer_texture) @buffer_texture_region.flip(false, true) @scale_factor, @elapsed = 0 load_shader @is_setup = true else @initialized_systems.each(&:reset) end @is_hidden = false end def render(delta) return if @is_hidden @initialized_systems.each do |system| system.update(delta) unless @is_hidden end Gdx.gl.gl_viewport(@viewport.x, @viewport.y, @viewport.width, @viewport.height) @buffer_object.begin @batch.begin if @shader_program @batch.shader = @original_shader end Gdx.gl.gl_clear(GL20.GL_COLOR_BUFFER_BIT) @initialized_systems.each do |system| system.render(delta) unless @is_hidden end @batch.end @batch.get_projection_matrix.set_to_ortho2_d(0, 0, $game.width, $game.height) @batch.begin @interface_system.render(delta) unless @is_hidden @batch.end @buffer_object.end Gdx.gl.gl_viewport(@viewport.x, @viewport.y, @viewport.width, @viewport.height) Gdx.gl.gl_clear(GL20.GL_COLOR_BUFFER_BIT) @batch.begin if @shader_program @batch.shader = @shader_program @shader_program.set_uniformf("u_deltaTime", delta) @shader_program.set_uniformf("u_scaleFactor", @scale_factor.to_f) end @batch.draw(@buffer_texture_region, 0, 0, $game.width, $game.height) @batch.end end def resize(width, height) @scale_factor = 1 while $game.width * (@scale_factor + 1) <= width && $game.height * (@scale_factor + 1) <= height @scale_factor += 1 end new_width = $game.width * @scale_factor new_height = $game.height * @scale_factor crop_x = (width - new_width) / 2 crop_y = (height - new_height) / 2 @viewport = Rectangle.new(crop_x, crop_y, new_width, new_height) end def pause end def hide @is_hidden = true end def dispose @batch.dispose @atlas.dispose @font.dispose @sounds.values.each(&:dispose) @initialized_systems.each(&:dispose) end def load_shader vert = load_asset('post_vertex.glsl').read_string frag = load_asset('post_fragment.glsl').read_string @original_shader = SpriteBatch.create_default_shader @shader_program = ShaderProgram.new(vert, frag) unless @shader_program.is_compiled Gdx.app.log("Shader Error:", @shader_program.get_log) @shader_program = nil end end def render_debug @batch.begin @font.draw(@batch, debug_text, 8, 16) @batch.end end def debug_text "FPS: #{Gdx.graphics.get_frames_per_second}" end end
ambethia/LuckyPrincessNitro
bin/main.rb
ROOT_DIR = File.expand_path('../..', __FILE__) $: << ROOT_DIR + '/lib' $: << ROOT_DIR + '/lib/screens' $: << ROOT_DIR + '/lib/components' $: << ROOT_DIR + '/lib/factories' $: << ROOT_DIR + '/lib/systems' $: << ROOT_DIR + '/vendor' DEBUG = !$0['<'] RELATIVE_ROOT = DEBUG ? '' : 'lucky_princess_nitro/' require 'java' require 'gdx-backend-lwjgl-natives.jar' require 'gdx-backend-lwjgl.jar' require 'gdx-natives.jar' require 'gdx.jar' java_import com.badlogic.gdx.backends.lwjgl.LwjglApplication java_import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration java_import com.badlogic.gdx.graphics.Texture java_import com.badlogic.gdx.graphics.OrthographicCamera java_import com.badlogic.gdx.graphics.g2d.Animation java_import com.badlogic.gdx.graphics.g2d.BitmapFont java_import com.badlogic.gdx.graphics.g2d.ParticleEffect java_import com.badlogic.gdx.graphics.g2d.Sprite java_import com.badlogic.gdx.graphics.g2d.SpriteBatch java_import com.badlogic.gdx.graphics.g2d.TextureAtlas java_import com.badlogic.gdx.graphics.g2d.TextureRegion java_import com.badlogic.gdx.graphics.glutils.FrameBuffer java_import com.badlogic.gdx.graphics.glutils.ShaderProgram java_import com.badlogic.gdx.graphics.GL20 java_import com.badlogic.gdx.graphics.Pixmap java_import com.badlogic.gdx.math.Circle java_import com.badlogic.gdx.math.Intersector java_import com.badlogic.gdx.math.MathUtils java_import com.badlogic.gdx.math.Rectangle java_import com.badlogic.gdx.math.Vector2 java_import com.badlogic.gdx.math.Vector3 java_import com.badlogic.gdx.scenes.scene2d.InputListener java_import com.badlogic.gdx.ApplicationListener java_import com.badlogic.gdx.Game java_import com.badlogic.gdx.Gdx java_import com.badlogic.gdx.Input java_import com.badlogic.gdx.Screen if DEBUG require ROOT_DIR + '/tools/gdx-tools.jar' java_import com.badlogic.gdx.tools.imagepacker.TexturePacker2 TexturePacker2.process("#{ROOT_DIR}/assets/source/images", "#{ROOT_DIR}/assets", "sprites"); end require 'lucky_princess_nitro' unless $0 == "irb" config = LwjglApplicationConfiguration.new config.title = "Lucky Princess Nitro" config.useGL20 = true config.width = LuckyPrincessNitro::VIRTUAL_WIDTH * LuckyPrincessNitro::DEFAULT_SCALE config.height = LuckyPrincessNitro::VIRTUAL_HEIGHT * LuckyPrincessNitro::DEFAULT_SCALE $game = LuckyPrincessNitro.new LwjglApplication.new($game, config) while $game.is_running; sleep(1); end end
ambethia/LuckyPrincessNitro
lib/systems/camera_system.rb
<filename>lib/systems/camera_system.rb class CameraSystem < EntitySystem::System CAMERA_TRACKING_SPEED = 0.075 def setup entity = manager.create(:camera) @spatial = manager.attach(entity, SpatialComponent.new({ px: $game.width / 2, py: $game.height / 2 })) @camera = manager.attach(entity, CameraComponent.new({ object: OrthographicCamera.new })) @camera.object.set_to_ortho(false, $game.width, $game.height) @camera.object.position.set(@spatial.px, @spatial.py, 0) @viewport = Rectangle.new(0, 0, $game.width, $game.height) end def update(delta) player_id = manager.find(:player) if player_id && !$game.did_we_win_yet? player = manager.component(SpatialComponent, player_id) @speed = player.speed.abs @player_x = player.px @player_y = player.py @x_vector = Math.cos(player.bearing * Math::PI/180) @y_vector = Math.sin(player.bearing * Math::PI/180) else # Keep the camera scrolling in the direction the player was moving when they died @player_x += @x_vector * delta * @speed @player_y += @y_vector * delta * @speed @speed -= @speed * delta * 0.5 if @speed && @speed < 12 if $game.did_we_win_yet? $game.victory else $game.game_over end end end @x_offset = @player_x + (@x_vector * $game.width * 0.0035 * @speed) @y_offset = @player_y + (@y_vector * $game.height * 0.003 * @speed) @spatial.px = lerp(@spatial.px, @x_offset, CAMERA_TRACKING_SPEED) @spatial.py = lerp(@spatial.py, @y_offset, CAMERA_TRACKING_SPEED) @camera.object.position.set(@spatial.px, @spatial.py, 0) @camera.object.update $game.screen.batch.set_projection_matrix(@camera.object.combined) end def reset @speed = 120 end end
ambethia/LuckyPrincessNitro
lib/systems/interface_system.rb
class InterfaceSystem < EntitySystem::System RADAR_RANGE = 320 # game width RADAR_SCALE = 0.1 # 10% def render(delta) @elapsed ||= 0 case $game.screen when GameScreen draw_shields draw_radar draw_gems_collected draw_debug if DEBUG end @elapsed += delta end def draw_shields player_id = manager.find(:player) if player_id player = manager.component(PlayerComponent, player_id) ox, oy = 8, $game.height - 16 player.shields.times do |i| x = 8 + (ox * i) @batch.draw($game.screen.sprites[:player_shield], x, oy) end end end def draw_radar @batch.draw($game.screen.sprites[:radar], @radar_center_x - 32, @radar_center_y - 32) player_id = manager.find(:player) if player_id player_s = manager.component(SpatialComponent, player_id) player_v = Vector2.new(player_s.px, player_s.py) manager.entities(EnemyComponent).each_with_index do |enemy_id, i| enemy_s = manager.component(SpatialComponent, enemy_id) enemy_v = Vector2.new(enemy_s.px, enemy_s.py) if player_v.dst(enemy_v) < RADAR_RANGE vector = enemy_v.sub(player_v).mul(RADAR_SCALE) @batch.draw( @enemy_radar.get_key_frame(@elapsed + i, true), @radar_center_x + vector.x - 1.5, @radar_center_y + vector.y - 1.5 ) end end # Find the closest gem closest_gem_id = manager.components(ItemComponent).select { |i| i.type == :gem }.sort_by { |i| item_s = manager.component(SpatialComponent, i.entity) item_v = Vector2.new(item_s.px, item_s.py) player_v.dst(item_v) }.map(&:entity).first manager.entities(ItemComponent).each_with_index do |item_id, i| item_s = manager.component(SpatialComponent, item_id) item_v = Vector2.new(item_s.px, item_s.py) # if in range draw on radar, else draw the closest along the border distance = player_v.dst(item_v) if distance < RADAR_RANGE vector = item_v.sub(player_v).mul(RADAR_SCALE) @batch.draw( $game.screen.sprites[:gem_radar], @radar_center_x + vector.x - 1.5, @radar_center_y + vector.y - 1.5 ) else next unless item_id == closest_gem_id angle = item_v.sub(player_v).angle @batch.draw( $game.screen.sprites[:gem_radar], @radar_center_x + (30 * MathUtils.cos_deg(angle)) - 1.5, @radar_center_y + (30 * MathUtils.sin_deg(angle)) - 1.5 ) # write text for distance to nearest gem @font.draw(@batch, (distance/10).round.to_s, $game.width - 24, 12) end end end end def draw_gems_collected remaining = manager.components(ItemComponent).select { |i| i.type == :gem }.size collected = SpawnSystem::NUM_GEMS - remaining text = "#{collected}/#{SpawnSystem::NUM_GEMS}" @font.draw(@batch, text, $game.width - 26, $game.height - 6) end def draw_debug @font.draw(@batch, $game.screen.debug_text, 8, 16) end def setup @batch = $game.screen.batch [:player_shield, :radar, :gem_radar].each do |sprite| $game.screen.sprites[sprite] = $game.screen.atlas.create_sprite(sprite.to_s) end @enemy_radar = Animation.new(0.1, *[ $game.screen.atlas.create_sprite("enemy_radar", 1), $game.screen.atlas.create_sprite("enemy_radar", 2), $game.screen.atlas.create_sprite("enemy_radar", 3) ]) @radar_center_x = $game.width - (64/2) - 8 @radar_center_y = (64/2) + 8 @font = BitmapFont.new(load_asset("04b03.fnt"), load_asset("04b03.png"), false) end end
ambethia/LuckyPrincessNitro
lib/systems/player_system.rb
<filename>lib/systems/player_system.rb class PlayerSystem < EntitySystem::System ROTATION_SPEED = 220 MAX_SPEED = 110 MIN_SPEED = -40 ACCELERATION = 50 DECELERATION = 30 RATE_OF_FIRE = 0.1 BULLET_SPEED = 240 BULLET_RADIUS = 6 def update(delta) entity = manager.find(:player) return unless entity # dont update if there's no player! spatial = manager.component(SpatialComponent, entity) player = manager.component(PlayerComponent, entity) # Update speed. We automatically accelerate up the the max speed, # except when turning, when we lose some speed speed = spatial.speed speed += ACCELERATION * delta if speed > MAX_SPEED speed = MAX_SPEED elsif speed < MIN_SPEED speed = MIN_SPEED end spatial.speed = speed if player.is_turning_right spatial.bearing += ROTATION_SPEED * delta spatial.bearing = spatial.bearing % 360 spatial.speed -= DECELERATION * delta end if player.is_turning_left spatial.bearing += (ROTATION_SPEED * -1) * delta spatial.bearing = spatial.bearing % 360 spatial.speed -= DECELERATION * delta end if player.is_firing @last_fired ||= 0 @last_fired += delta if @last_fired >= RATE_OF_FIRE @last_fired = 0 manager.factory.bullet do |bullet| bullet.owner = manager.find(:player) bullet.type = :player bullet.px = spatial.px bullet.py = spatial.py bullet.bearing = spatial.bearing end $game.screen.sounds[:player_bullet].play(0.25) end end if player.shields <= 0 # Enemy death manager.destroy(entity) end end def setup screen = $game.screen atlas = screen.atlas frames = [] # 0 frames[0] = atlas.create_sprite("player_c0") frames[1] = atlas.create_sprite("player_c1") # 45 frames[2] = atlas.create_sprite("player_b0") frames[3] = atlas.create_sprite("player_b1") # 90 frames[4] = atlas.create_sprite("player_a0") frames[5] = atlas.create_sprite("player_a1") # 135 frames[6] = atlas.create_sprite("player_b0") frames[6].flip(true, false) frames[7] = atlas.create_sprite("player_b1") frames[7].flip(true, false) # 180 frames[8] = atlas.create_sprite("player_c0") frames[8].flip(true, false) frames[9] = atlas.create_sprite("player_c1") frames[9].flip(true, false) # 225 frames[10] = atlas.create_sprite("player_b0") frames[10].flip(true, true) frames[11] = atlas.create_sprite("player_b1") frames[11].flip(true, true) # 270 frames[12] = atlas.create_sprite("player_a0") frames[12].flip(false, true) frames[13] = atlas.create_sprite("player_a1") frames[13].flip(false, true) # 315 frames[14] = atlas.create_sprite("player_b0") frames[14].flip(false, true) frames[15] = atlas.create_sprite("player_b1") frames[15].flip(false, true) $game.screen.sprites[:player] = { 0 => Animation.new(0.25, *frames[0..1]), 45 => Animation.new(0.25, *frames[2..3]), 90 => Animation.new(0.25, *frames[4..5]), 135 => Animation.new(0.25, *frames[6..7]), 180 => Animation.new(0.25, *frames[8..9]), 225 => Animation.new(0.25, *frames[10..11]), 270 => Animation.new(0.25, *frames[12..13]), 315 => Animation.new(0.25, *frames[14..15]) } bullet_sprites = { 0 => atlas.create_sprite("bullet", 0), 45 => atlas.create_sprite("bullet", 1), 90 => atlas.create_sprite("bullet", 2), 135 => atlas.create_sprite("bullet", 1), 180 => atlas.create_sprite("bullet", 0), 225 => atlas.create_sprite("bullet", 1), 270 => atlas.create_sprite("bullet", 2), 315 => atlas.create_sprite("bullet", 1) } bullet_sprites[90].flip(false, false) bullet_sprites[135].flip(true, false) bullet_sprites[180].flip(true, false) bullet_sprites[225].flip(true, true) bullet_sprites[270].flip(false, true) bullet_sprites[315].flip(false, true) $game.screen.sprites[:player_bullets] = bullet_sprites [:player_spawn, :player_bullet, :player_death, :shield_damage, :bullet_destruct, :pickup_gem].each do |sound| $game.screen.sounds[sound] = Gdx.audio.new_sound(load_asset("#{sound}.ogg")) end end end
ambethia/LuckyPrincessNitro
lib/screens/splash_screen.rb
class SplashScreen < BaseScreen def setup @systems = %w[ Input Splash ] end end
ambethia/LuckyPrincessNitro
lib/entity_system.rb
<filename>lib/entity_system.rb module EntitySystem end require 'entity_system/manager' require 'entity_system/component' require 'entity_system/factory' require 'entity_system/system'
ambethia/LuckyPrincessNitro
lib/systems/ranged_cull_system.rb
<reponame>ambethia/LuckyPrincessNitro<gh_stars>1-10 class RangedCullSystem < EntitySystem::System def update(delta) camera = manager.component(CameraComponent, manager.find(:camera)).object camera_position = camera.position each(RangedCullComponent) do |entity, component| spatial = manager.component(SpatialComponent, entity) distance = camera_position.dst(Vector3.new(spatial.px, spatial.py, 0)) if distance > component.range manager.destroy(entity) end end end end
ipublic/marketplace
app/models/subscriptions/feature.rb
<gh_stars>0 module Subscriptions class Feature include Mongoid::Document include Mongoid::Timestamps FEATURES = { # Level: Routing aca_shop_market_feature: { key: :aca_shop_market, title: "ACA SHOP Market", description: "ACA Small Business Health Options (SHOP) Portal" }, # Level: Routing aca_individual_market_feature: { key: :aca_individual_market, title: "ACA Individual Market", description: "ACA Individual Market Portal"}, # Level: Routing fehb_market_feature: { key: :fehb_market, title: "Congress and Federal Employee Market", description: "Federal Employee Health Benefits Portal"}, # Level: Routing ea_broker_portal_feature: { key: :ea_broker_portal, title: "Broker Agency Portal", description: "Web portal for Broker Agencies to manage customers and their benefits" }, # Level: Routing ea_ga_portal_feature: { key: :ea_ga_portal, title: "General Agency Portal", description: "Web portal for General Agencies to support Broker Agencies" }, # Level: Routing broker_quoting_tool_feature: { key: :bqt_portal, title: "Broker Quoting Tool", description: "" }, # Level: Routing ea_ops_portal_feature: { key: :ea_ops_portal, title: "Business Operations Portal", description: "Web portal for site business staff to manage site customers stakeholders and operations" }, # Level: Routing ea_ops_classic_portal_feature: { key: :ea_ops_classic_portal, title: "Business Operations Portal (classic)", description: "Web portal for site business staff to manage site products, customers, stakeholders and operations" }, # Level: Routing ea_plan_mgt_portal_feature: { key: :ea_plan_mgt_portal, title: "Plan Management Portal", description: "Web portal for site plan management staff to manage benefit products" }, # Level: Enterprise enterprise_admin_portal: { key: :enterprise_admin_portal, title: "Web portal for IT staff to configure and administer the site system and services", description: "" }, # Level: Enterprise ea_component: { key: :ea_component, title: "Enroll Application Component", description: "" }, # Level: Enterprise edi_db_classic_component: { key: :edi_db_classic_component, title: "EDI Database Component (classic)", description: "" }, # Level: Enterprise edi_db_component: { key: :edi_db_component, title: "EDI Database Component", description: "" }, # Level: Enterprise ledger_component: { key: :ledger_component, title: "Ledger Component", description: "Web portal for accounts, billing and payment" }, # Level: Enterprise notice_component: { key: :notice_component, title: "Notice Component", description: "" }, # Level: Enterprise trans_gw_component: { key: :trans_gw_component, title: "Transport Gateway Component", description: "" }, } has_many :subscriptions, class_name: 'Subscriptions::Subscription' field :key, type: Symbol field :title, type: String field :description, type: String validates_presence_of :key, :title, :description index({ key: 1 }, { unique: true }) def tenants Tenant.in(id: subscriptions.pluck(:tenant_id)) end end end
ipublic/marketplace
app/models/timespans/month_timespan.rb
module Timespans class MonthTimespan < Timespan attr_readonly :year, :month, :begin_on, :end_on field :year, type: Integer field :month, type: Integer belongs_to :calendar_year_timespan, class_name: 'Timespans::CalendarYearTimespan' validates_presence_of :year validates :month, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 12 } # Mongoid stores inherited classes as STI. Year index is created in calendar_year_timespan index({ month: 1 }) scope :month_of_year, ->(year, month){} def beginning_of_month(new_year, new_month) Date.new(new_year, new_month) end def end_of_month(new_year, new_month) Date.new(new_year, new_month).end_of_month end private def initialize_timespan if year.present? && month.present? write_attribute(:begin_on, beginning_of_month(year, month)) if begin_on.blank? write_attribute(:end_on, end_of_month(year, month)) if end_on.blank? write_attribute(:title, "#{year} #{Date::ABBR_MONTHNAMES[month]}") if title.blank? end end end end
ipublic/marketplace
spec/factories/integrations_get_priority_mail_receipts.rb
FactoryBot.define do factory :integrations_get_priority_mail_receipt, class: 'Integrations::GetPriorityMailReceipt' do end end
ipublic/marketplace
app/models/dispatcher/tasks/task.rb
<reponame>ipublic/marketplace class Dispatcher::Tasks::Task include Mongoid::Document end
ipublic/marketplace
spec/factories/filter_tokens.rb
FactoryBot.define do factory :filter_token do name { "MyString" } granted { false } end end
ipublic/marketplace
spec/factories/wages_wage_reports.rb
FactoryBot.define do factory :wages_wage_report, class: 'Wages::WageReport' do submission_kind { :original } filing_method_kind { :upload } total_wages { 40_125.32 } excess_wages { 5_125.11 } taxable_wages { total_wages - excess_wages } association :wage_entries association :organization_party association :timespans end end
ipublic/marketplace
spec/factories/notices_ui_delinquency_notices.rb
<filename>spec/factories/notices_ui_delinquency_notices.rb FactoryBot.define do factory :notices_ui_delinquency_notice, class: 'Notices::UiDelinquencyNotice' do end end
ipublic/marketplace
spec/factories/integrations_release_liens.rb
FactoryBot.define do factory :integrations_release_lien, class: 'Integrations::ReleaseLien' do end end
ipublic/marketplace
app/models/dispatcher/workers/echo_worker.rb
<filename>app/models/dispatcher/workers/echo_worker.rb class Dispatcher::Workers::EchoWorker include Mongoid::Document end
ipublic/marketplace
app/models/dispatcher/workflow.rb
module Dispatcher class Workflow include Mongoid::Document belongs_to :processable, polymorphic: true # embeds_many field :tasks, type: Array, default: [] end end
ipublic/marketplace
app/models/wages/tip_wage_entry.rb
module Wages class TipWageEntry < Wage field :hours_worked, type: Integer end end
ipublic/marketplace
spec/controllers/api/v3/echo_controller_spec.rb
<filename>spec/controllers/api/v3/echo_controller_spec.rb require 'rails_helper' RSpec.describe Api::V3::EchoController, type: :controller do end
ipublic/marketplace
spec/factories/notices_ui_blocked_claim_eligible_notices.rb
<gh_stars>0 FactoryBot.define do factory :notices_ui_blocked_claim_eligible_notice, class: 'Notices::UiBlockedClaimEligibleNotice' do end end
ipublic/marketplace
spec/factories/subscriptions_subscribeds.rb
FactoryBot.define do factory :subscriptions_subscribed, class: 'Subscriptions::Subscribed' do end end
ipublic/marketplace
spec/factories/parties_parties.rb
FactoryBot.define do factory :parties_party, class: 'Parties::Party' do end end
ipublic/marketplace
app/models/financial_accounts/pfl_financial_account.rb
module FinancialAccounts class PflFinancialAccount < FinancialAccount include Mongoid::Document field :pfl_tax_rate, type: Float, default: 0.0 field :pfl_wage_filing_schedule, type: Symbol end end
ipublic/marketplace
app/models/quanta/time_period.rb
class Quanta::TimePeriod include Mongoid::Document end
ipublic/marketplace
app/models/bakery/cupcake_factory.rb
module Bakery class CupcakeFactory def self.call(**options) new(options).cupcake end def initialize(**options) @cupcake = Bakery::Cupcake.new @cupcake.cc_id = options[:cc_id] if options[:cc_id].present? bake_cupcake frost_cupcake add_sprinkles self end def bake_cupcake @cupcake.cake = Bakery::Cupcake::CAKE_KINDS.sample end def frost_cupcake @cupcake.frosting = Bakery::Cupcake::FROSTING_KINDS.sample end def add_sprinkles(shake_count = 2) count = 0 while count < shake_count @cupcake.sprinkles << Bakery::Sprinkle.new().sample_sprinkle count += 1 end end def cupcake @cupcake end end end
ipublic/marketplace
app/models/dispatcher/routing_slip.rb
module Dispatcher WORK_ITEM_QUEUE = "" class RoutingSlip def initialize(workflow) workflow.tasks.each { |task| WORK_ITEM_QUEUE.enqueue task } @completed_tasks = workflow.completed_tasks end def is_completed? next_task.count == 0 end def is_in_progress? completed_tasks.count > 0 end def process_next_task current_task = WORK_ITEM_QUEUE.dequeue return if current_task.blank? task = Task.new(current_task.task_kind) begin result = task.do_work(current_task) completed_tasks.push(result) if result.present? rescue => e puts "#{e.class}: #{e.message}" end result end def progresss_uri next_task.peek.task_kind.task_queue_address unless is_completed? end def compensation_uri completed_tasks.peek.task_kind.compensation_queue_address if is_in_progress? end def undo_last raise StandardError.new("invalid operation") if is_in_progress? current_task = completed_tasks.pop task = current_task.task_kind.new begin task.compensate(current_task) rescue => e puts "#{e.class}: #{e.message}" end end end end
ipublic/marketplace
app/models/financial_accounts/contribution_rate.rb
<filename>app/models/financial_accounts/contribution_rate.rb module FinancialAccounts class ContributionRate include Mongoid::Document field :effective_on, type: Date field :determined_at, type: Time, default: TimeKeeper.date_of_record embedded_in :financial_account, class_name: 'FinancialAccounts::FinancialAccount' belongs_to :timespan, class_name: 'Timespans::Timespan' end end
ipublic/marketplace
spec/factories/integrations_generate_notices.rb
FactoryBot.define do factory :integrations_generate_notice, class: 'Integrations::GenerateNotice' do end end
ipublic/marketplace
app/serializers/sprinkle_serializer.rb
<gh_stars>0 class SprinkleSerializer include FastJsonapi::ObjectSerializer attributes :id, :color, :shape end
ipublic/marketplace
spec/factories/financial_accounts_ui_contribution_rates.rb
FactoryBot.define do factory :financial_accounts_ui_contribution_rate, class: 'FinancialAccounts::UiContributionRate' do end end
ipublic/marketplace
app/models/determinations/group_ui_liability_determination.rb
<filename>app/models/determinations/group_ui_liability_determination.rb<gh_stars>0 class Determinations::GroupUiLiabilityDetermination include Mongoid::Document end
ipublic/marketplace
app/models/products/product.rb
<gh_stars>0 class Products::Product include Mongoid::Document end
ipublic/marketplace
app/models/parties/organization_party.rb
<gh_stars>0 module Parties class OrganizationParty < Party # Shared Unemployment Insurance and PFL ID field :entity_id, type: Integer # Federal Employer ID Number field :fein, type: String # Registered legal name field :legal_name, type: String # Doing Business As (alternate name) field :dba, type: String field :entity_kind, type: Symbol field :is_foreign_entity, type: Boolean # DC Corporation? has_many :wage_reports, class_name: "Wages::WageReport" embeds_many :naics_classifications, class_name: 'Parties::NaicsClassification' validates :fein, presence: true, length: { is: 9, message: "%{value} is not a valid FEIN" }, numericality: true #uniqueness: true # embeds_many :documents, as: :documentable validates_presence_of :fein, :legal_name, :is_foreign_entity # index({ entity_id: 1 }, { unique: true}) index({ legal_name: 1 }) index({ dba: 1 }, { sparse: true }) index({ fein: 1 }, { unique: true, sparse: true }) alias_method :is_foreign_entity?, :is_foreign_entity # Strip non-numeric characters def fein=(new_fein) numeric_fein = new_fein.to_s.gsub(/\D/, '') write_attribute(:fein, numeric_fein) @fein = numeric_fein end class << self def search_hash(s_rex) search_rex = ::Regexp.compile(::Regexp.escape(s_rex), true) { "$or" => ([ {"legal_name" => search_rex}, {"fein" => search_rex}, ]) } end end end end
ipublic/marketplace
spec/factories/parties_person_names.rb
FactoryBot.define do factory :parties_person_name, class: 'Parties::PersonName' do end end
ipublic/marketplace
app/models/address.rb
class Address include Mongoid::Document include Mongoid::Timestamps KINDS = %W(home work mailing) OFFICE_KINDS = %W(primary mailing branch) embedded_in :addressable, polymorphic: true field :kind, type: String field :address_1, type: String field :address_2, type: String, default: "" # The name of the city where this address is located field :city, type: String # The name of the county where this address is located field :county, type: String, default: '' # The name of the U.S. state where this address is located field :state, type: String # The postal zip code where this address is located field :zip, type: String end
ipublic/marketplace
app/models/integrations/redetermine_ui_contribution_rate.rb
class Integrations::RedetermineUiContributionRate include Mongoid::Document end
ipublic/marketplace
spec/models/parties/party_relationship_kind_spec.rb
<reponame>ipublic/marketplace require 'rails_helper' RSpec.describe Parties::PartyRelationshipKind, type: :model, dbclean: :after_each do it { is_expected.to be_mongoid_document } it { is_expected.to have_timestamps } it { is_expected.to have_fields(:key, :title, :description)} let(:key) { :battle_opponents } let(:title) { "Battle Opponents" } let(:scott_pilgrim_role) { Parties::PartyRoleKind.create!(key: :hero) } let(:bollywood_evil_ex_role) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:skateboarder_evil_ex_role) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:vegan_evil_ex_role) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:exgirlfriend_evil_ex_role) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:twin_one_evil_ex_role) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:twin_two_evil_ex_role) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:gman_evil_ex_role) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:subject_party_role_kind) { Parties::PartyRoleKind.create!(key: :hero) } let(:object_party_role_kind) { Parties::PartyRoleKind.create!(key: :evil_ex) } let(:party_role_kinds) { [subject_party_role_kind, object_party_role_kind] } let(:params) do { key: key, title: title, party_role_kinds: party_role_kinds, } end describe "A new model instance" do context "with no arguments" do subject { described_class.new } it "should not be valid" do subject.validate expect(subject).to_not be_valid end end context "with both key and title" do let(:other_key) { :other_key } let(:other_title) { 'other_title' } subject { described_class.new(key: other_key, title: other_title) } it "should set the assigned values" do subject.validate expect(subject.key).to eq other_key expect(subject.title).to eq other_title end end context "with no key and no title" do subject { described_class.new(params.except(*[:key, :title])) } it "should not be valid" do subject.validate expect(subject).to_not be_valid expect(subject.errors[:key].first).to match(/can't be blank/) end end context "with a key and no title" do subject { described_class.new(params.except(:title)) } it "should be valid" do subject.validate expect(subject).to be_valid end end context "with a title and no key" do subject { described_class.new(params.except(:key)) } it "should be valid" do subject.validate expect(subject).to be_valid end end context "with no party_role_kinds" do subject { described_class.new(params.except(:party_role_kinds)) } it "should be valid" do subject.validate expect(subject).to_not be_valid expect(subject.errors[:party_role_kinds].first).to match(/must provide a specific role pair/) end end context "with all required arguments" do subject {described_class.new(params) } it "should be valid" do subject.validate expect(subject).to be_valid end context "and it is saved" do it "should save" do expect(subject.save).to eq true end context "it should be findable" do before { subject.save! } it "should return the instance" do expect(described_class.find(subject.id.to_s)).to eq subject end end end end end end
ipublic/marketplace
spec/models/roles/role_factory_spec.rb
require 'rails_helper' RSpec.describe Roles::RoleFactory, type: :model, dbclean: :after_each do let(:hero_party_role_kind_key) { :hero } let(:evil_ex_party_role_kind_key) { :evil_ex } let(:current_first_name) { 'Scott' } let(:current_last_name) { 'Pilgrim' } let(:scott_pilgrim_party) { Parties::PersonParty.create!(current_first_name: current_first_name, current_last_name: current_last_name) } let!(:hero_party_role_kind) { Parties::PartyRoleKind.create!(key: hero_party_role_kind_key) } let!(:evil_ex_party_role_kind) { Parties::PartyRoleKind.create!(key: evil_ex_party_role_kind_key) } describe 'Given a PersonParty with no PartyRoles and some party_role_kinds' do it "PartyRoles should be empty" do expect(scott_pilgrim_party.party_roles.size).to eq 0 end context 'and a PartyRole is added' do it 'the PersonParty should now reference the added PartyRole' do factory = Roles::RoleFactory.new(scott_pilgrim_party, hero_party_role_kind_key) expect(factory.party_role.party_role_kind).to eq hero_party_role_kind expect(scott_pilgrim_party.party_roles.size).to eq 1 expect(scott_pilgrim_party.party_roles.first.party_role_kind).to eq hero_party_role_kind scott_pilgrim_party.validate expect(scott_pilgrim_party).to be_valid end end context 'and the same PartyRole is added again' do it 'should block addition of the duplicate PartyRole' do factory = Roles::RoleFactory.new(scott_pilgrim_party, hero_party_role_kind_key) expect(scott_pilgrim_party.party_roles.size).to eq 1 expect(scott_pilgrim_party.party_roles.first.party_role_kind).to eq hero_party_role_kind duplicate_factory = Roles::RoleFactory.new(scott_pilgrim_party, hero_party_role_kind_key) expect(duplicate_factory.party_role).to eq nil end end end end
ipublic/marketplace
spec/models/integrations/assign_ui_case_spec.rb
require 'rails_helper' RSpec.describe Integrations::AssignUiCase, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
ipublic/marketplace
app/models/subscriptions/tenant.rb
<gh_stars>0 module Subscriptions class Tenant include Mongoid::Document include Mongoid::Timestamps has_many :subscriptions, class_name: 'Subscriptions::Subscription' field :site_key, type: Symbol field :name, type: String validates_presence_of :site_key, :name index({ site_key: 1 }, { unique: true }) def features Subscriptions::Feature.in(id: subscriptions.pluck(:feature_id)) end def flipper_id subdomain end private def assign_schema self.schema = subdomain end end end
ipublic/marketplace
spec/factories/currents.rb
FactoryBot.define do factory :current do end end
ipublic/marketplace
spec/factories/taxes_taxes.rb
FactoryBot.define do factory :taxes_tax, class: 'Taxes::Tax' do end end
ipublic/marketplace
app/models/financial_accounts/ui_financial_account.rb
module FinancialAccounts class UiFinancialAccount < FinancialAccount # Account states: # Current # Overdue - oustanading balance last day of every month (reimburse, contribute) # Delinquent - 60 days after delinquency notice, system identifies employers with missing reports, calculates estimated report # Quarter Delinquent - (management designation) 60 days after end of quarter. Generate Deliquency Notice # Closed # Reason: Written Off include Mongoid::Document # Initial date employer became liable for UI tax field :status, type: Symbol, default: :active field :ledger_system_account_id, type: BSON::ObjectId field :initial_liability_date, type: Date #, default: ->{ TimeKeeper.date_of_record } field :current_payment_kind, type: Symbol#, default: :uits_contributing field :current_wage_filing_schedule, type: Symbol#, default: :uits_qtr_filer field :current_administrative_rate, type: Float, default: 0.0 field :current_contribution_rate, type: Float, default: 0.0 #embeds_many :filing_statuses # wage report filed for timespans #embeds_many :payment_status # financial transactions for timespans validates_presence_of :initial_liability_date, :status, :current_payment_kind, :current_wage_filing_schedule def current_balance financial_transactions.reduce(0.0) do |total, transaction| total += transaction.amount || 0 end end end end
ipublic/marketplace
spec/factories/integrations_generate_bills.rb
FactoryBot.define do factory :integrations_generate_bill, class: 'Integrations::GenerateBill' do end end
ipublic/marketplace
spec/factories/financial_accounts_ui_financial_accounts.rb
FactoryBot.define do factory :financial_accounts_ui_financial_account, class: 'FinancialAccounts::UiFinancialAccount' do end end
ipublic/marketplace
app/models/quanta/sequence.rb
<filename>app/models/quanta/sequence.rb class Quanta::Sequence include Mongoid::Document end
ipublic/marketplace
app/models/integrations/assign_ui_case.rb
<gh_stars>0 class Integrations::AssignUiCase include Mongoid::Document end
ipublic/marketplace
app/models/quanta/duration.rb
<reponame>ipublic/marketplace module Quanta class Duration def initialize(duration) @duration = duration end # Converts an object of this instance into a database friendly value. def mongoize @duration.iso8601 end class << self # Get the object as it was stored in the database, and instantiate # this custom class from it. def demongoize(object) ActiveSupport::Duration.parse(object) end # Takes any possible object and converts it to how it would be # stored in the database. def mongoize(object) case object when Duration then object.mongoize when Integer then ActiveSupport::Duration.build(object).mongoize else object end end # Converts the object that was supplied to a criteria and converts it # into a database friendly form. def evolve(object) case object when Duration then object.mongoize else object end end end end end
ipublic/marketplace
spec/factories/financial_accounts_party_ledger_account_balances.rb
FactoryBot.define do factory :financial_accounts_party_ledger_account_balance, class: 'FinancialAccounts::PartyLedgerAccountBalance' do end end
ipublic/marketplace
app/models/roles/relationship_role_factory.rb
module Roles class RelationshipRoleFactory attr_accessor :party, :related_party, :party_relationship def self.call(party, party_role_kind_key, party_relationship_kind_key, related_party) build(party, args).party_role end # look up party_role_kind # look up party_relationship kind # verify the party_relationship includes the passed party_role_kind in the relationship pair # build party_roles for both the source party and related party # instantiate a new party_relationship instance populated with the party_role instances # validate the relationship isn't already present for these parties def initialize(party, party_role_kind_key, party_relationship_kind_key, related_party) @party = party @party_role_kind_key = party_role_kind_key @party_relationship_kind_key = party_relationship_kind_key @related_party = related_party @party_relationship_kind = nil @party_relationship = nil @party_role_kind = nil @party_role = nil @related_party_role_kind = nil @related_party_role = nil find_party_role_kind find_party_relationship_kind verify_party_role_pair build_party_role build_related_party_role initilize_party_relationship validate_unique_relationship end def find_party_role_kind @party_role_kind = Parties::PartyRoleKind.find_by(key: @party_role_kind_key) end def find_party_relationship_kind @party_relationship_kind = Parties::PartyRelationshipKind.find_by(key: @party_relationship_kind_key) end def verify_party_role_pair if @party_relationship_kind.party_role_kinds.include?(@party_role_kind) @related_party_role_kind = (@party_relationship_kind.party_role_kinds - @party_role_kind.to_a).first else # Error condition, the passed party_role_kind isn't in the relationshiop definition end end def initilize_party_relationship @party_relationship = Parties::PartyRelationship.new(party_relationship_kind: @party_relationship_kind, party_roles: [@party_role, @related_party_role]) end def validate_unique_relationship # Error condition, this relationship already exists # compare active relationship with same relationship_kind and party pair # if @party.active_party_roles.detect { |role| @party_relationship_kind.present && # (role.party_relationship_kind == @party_relationship_kind) && # (role.party_role_kind == party_role_kind) # } # end end def build_party_role @party_role = party.party_roles.build(party_role_kind: @party_role_kind) end def build_related_party_role @related_party_role = related_party.party_roles.build(party_role_kind: @related_party_role_kind) end def party @party end def related_party @related_party end def party_relationship @party_relationship end end end
ipublic/marketplace
spec/factories/financial_accounts_financial_account_factories.rb
FactoryBot.define do factory :financial_accounts_financial_account_factory, class: 'FinancialAccounts::FinancialAccountFactory' do end end
ipublic/marketplace
app/models/products/unemployment_insurance.rb
class Products::UnemploymentInsurance include Mongoid::Document PAYMENT_TYPES = [:contributory] WAGE_FILING_SCHEDULES = [:quarterly, :annually] field :payment_type, type: Symbol field :wage_filing_schedule, type: Symbol end
ipublic/marketplace
spec/factories/wages_exempt_wage_entries.rb
<gh_stars>0 FactoryBot.define do factory :wages_exempt_wage_entry, class: 'Wages::ExemptWageEntry' do end end
ipublic/marketplace
app/models/financial_accounts/ui_contribution_rate.rb
module FinancialAccounts class UiContributionRate < ContributionRate include Mongoid::Document EMPLOYER_TAXABLE_WAGE_MAX = 2_000_000 EMPLOYEE_TAXABLE_WAGE_MAX = 9_000 # RATE_KINDS = [:unempmloyment_insurance, :administrative_fee] # field :rate_kind, type: Symbol field :ui_wage_filing_schedule, type: Symbol field :ui_tax_rate, type: Float, default: 0.0 field :ui_administrative_rate, type: Float, default: 0.0 field :ui_combined_rate, type: Float before_save :set_ui_combined_rate def calculate_ui_combined_rate ui_tax_rate - ui_administrative_rate end private def set_ui_combined_rate write_attribute(:ui_combined_rate, calculate_ui_combined_rate) if ui_combined_rate.blank? end end end
ipublic/marketplace
app/models/fees/interest_fee.rb
<gh_stars>0 class Fees::InterestFee include Mongoid::Document end
ipublic/marketplace
spec/factories/products_individual_health_insurances.rb
FactoryBot.define do factory :products_individual_health_insurance, class: 'Products::IndividualHealthInsurance' do end end
ipublic/marketplace
spec/factories/cases_cases.rb
<filename>spec/factories/cases_cases.rb FactoryBot.define do factory :cases_case, class: 'Cases::Case' do end end
ipublic/marketplace
spec/factories/integrations_register_employers.rb
FactoryBot.define do factory :integrations_register_employer, class: 'Integrations::RegisterEmployer' do end end
ipublic/marketplace
spec/factories/dispatcher_activities_activities.rb
<reponame>ipublic/marketplace FactoryBot.define do factory :dispatcher_activities_activity, class: 'Dispatcher::Activities::Activity' do end end
ipublic/marketplace
app/models/fees/premium_fee.rb
<reponame>ipublic/marketplace<filename>app/models/fees/premium_fee.rb class Fees::PremiumFee include Mongoid::Document end
ipublic/marketplace
app/models/sagas/activities/activity_host.rb
class Sagas::Activities::ActivityHost def initialize(action, routing_slip) # send_message = send_message end def accept_message?(uri, routing_slip) # examine uri end def process_forward_message(routing_slip) return if routing_slip.is_completed? # if current step is successful, proceed. otherwise go to the unwind path if routing_slip.process_next? # recursion stands for passing context via message # routing_slip can be fully serialized and passed bewteen systems send_message(routing_slip.progress_uri, routing_slip) else # pass message to unwind message route send_message(routing_slip.compensation_uri) end end def process_backward_message(routing_slip) if routing_slip.is_in_progress? # undo_last can put new work on the routing_slip and return false to # go back on the foward path if routing_slip.undo_last # recursion stands for passing context via message # routing_slip can be fully serialized and passed bewteen systems send_message(routing_slip.compensation_uri, routing_slip) else send_message(routing_slip.progress_uri, routing_slip) end end end end
ipublic/marketplace
spec/factories/parties_party_roles.rb
<gh_stars>0 FactoryBot.define do factory :parties_party_role, class: 'Parties::PartyRole' do end end
ipublic/marketplace
spec/factories/fees_unemployment_insurance_taxes.rb
<filename>spec/factories/fees_unemployment_insurance_taxes.rb FactoryBot.define do factory :fees_unemployment_insurance_tax, class: 'Fees::UnemploymentInsuranceTax' do end end
ipublic/marketplace
spec/models/sagas/activities/activity_host_spec.rb
require 'rails_helper' RSpec.describe Sagas::Activities::ActivityHost, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
ipublic/marketplace
spec/factories/dispatcher_tasks_notice_tasks.rb
<reponame>ipublic/marketplace<gh_stars>0 FactoryBot.define do factory :dispatcher_tasks_notice_task, class: 'Dispatcher::Tasks::NoticeTask' do end end
ipublic/marketplace
spec/factories/determinations_ui_determination_services.rb
<filename>spec/factories/determinations_ui_determination_services.rb FactoryBot.define do factory :determinations_ui_determination_service, class: 'Determinations::UiDeterminationService' do end end
ipublic/marketplace
app/models/timespans/quarter_year_timespan.rb
module Timespans class QuarterYearTimespan < Timespan attr_readonly :year, :quarter, :begin_on, :end_on field :year, type: Integer field :quarter, type: Integer belongs_to :calendar_year_timespan, class_name: 'Timespans::CalendarYearTimespan' validates_presence_of :year validates :quarter, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 4 } # Mongoid stores inherited classes as STI. Year index is created in calendar_year_timespan index({quarter: 1 }) scope :quarter_of_year, ->(year, quarter){} def beginning_of_quarter(new_year, new_quarter) Date.new(new_year, new_quarter * 3 - 2) if (1..4).cover? new_quarter end def end_of_quarter(new_year, new_quarter) Date.new(new_year, new_quarter * 3, -1) if (1..4).cover? new_quarter end private def initialize_timespan if year.present? && quarter.present? write_attribute(:begin_on, beginning_of_quarter(year, quarter)) if begin_on.blank? write_attribute(:end_on, end_of_quarter(year, quarter)) if end_on.blank? write_attribute(:title, "#{year} Q#{quarter}") if title.blank? end end end end
ipublic/marketplace
lib/mongoid_toolkit/model_tree.rb
module MongoidToolkit class ModelTree SYSTEM_MODEL_NAMES = ["Mongoid::GridFs::Fs::File", "Mongoid::GridFs::Fs::Chunk", "ActionDispatch::Session::MongoidStore::Session"] SYSTEM_MODELS = SYSTEM_MODEL_NAMES.reduce([]) { |model_name| mongoid_model_for(model_name) } PARENT_ASSOCIATIONS = [:embeds_many, :has_many, :embeds_one, :has_one] CHILD_ASSOCIATIONS = [:embedded_in, :belongs_to] attr_reader :value # TODO: update Mongoid Relations to Association (available starting v7) # TODO: move tree into class instance def initialize(value) @value = value @children = [] end def <<(value) subtree = ModelTree.new(value) @children = subtree return subtree end class << self def models Mongoid.models end def application_models models - SYSTEM_MODELS end def parent_models application_models.reduce([]) { |list, model| list << model if parent_relations_for(model).size == 0; list } end def child_models application_models - parent_models end def model_class_names return @model_class_names if defined? @model_class_names @model_class_names = application_models.reduce([]) { |list, model| list << model.name } end def models_sorted return @models_sorted if defined? @models_sorted sorted_model_class_names = model_class_names.sort @models_sorted = sorted_model_class_names.each { |class_name| mongoid_model_for(class_name) } end def child_models_for(model) children = immediate_child_models_for(model) if children.size > 0 [model] + children.reduce([]) { |list, child| list << child_models_for(child) } else return [model] end end def immediate_child_models_for(model, ordered = true) relation_class_names = immediate_relation_class_names_for(model).reduce([]) do |list, relation| relation_name = relation_class_name_for(relation) list << relation_name unless relation_name == model.name list end relation_class_names.sort! if ordered relation_class_names.reduce([]) { |list, class_name| list << mongoid_model_for(class_name); list.compact } end def mongoid_model_for(class_name) class_name.constantize if model_class_names.include?(class_name) end def parent_relations_for(model) model.relations.reduce([]) { |list, relation| list << relation if CHILD_ASSOCIATIONS.include?(relation_macro_for(relation)); list } end def immediate_relation_class_names_for(model) model.relations.reduce([]) { |list, relation| list << relation if PARENT_ASSOCIATIONS.include?(relation_macro_for(relation)); list } end def relation_class_name_for(relation) relation[1].class_name end def relation_macro_for(relation) relation[1].macro end end end end
ipublic/marketplace
db/seedfiles/party_roles_and_relationships_seed.rb
<reponame>ipublic/marketplace<filename>db/seedfiles/party_roles_and_relationships_seed.rb puts "*"*80 puts "Populating Roles" puts "*"*80 ## PersonParty Roles ## Parties::PartyRoleKind.create!(key: :employee, title: 'Employee') Parties::PartyRoleKind.create!(key: :owner_or_officer, title: 'Owner/Officer') Parties::PartyRoleKind.create!(key: :contractor, title: 'Contractor') Parties::PartyRoleKind.create!(key: :responsible_party, title: 'Responsible Party') Parties::PartyRoleKind.create!(key: :self, title: 'Self') Parties::PartyRoleKind.create!(key: :spouse, title: 'Spouse') Parties::PartyRoleKind.create!(key: :domestic_partner, title: 'Domestic Partner') Parties::PartyRoleKind.create!(key: :child, title: 'Child') Parties::PartyRoleKind.create!(key: :dependent, title: 'Dependent') Parties::PartyRoleKind.create!(key: :contact, title: 'Contact') # UITS/PFL Parties::PartyRoleKind.create!(key: :ui_claiment, title: 'Unemployment Insurance Claiment') Parties::PartyRoleKind.create!(key: :pfl_claiment, title: 'Paid Family Leave Claiment') ## OrganizationParty Roles ## Parties::PartyRoleKind.create!(key: :parent_organization, title: 'Parent Organization') Parties::PartyRoleKind.create!(key: :subsiary, title: 'Subsiary') Parties::PartyRoleKind.create!(key: :department, title: 'Department') Parties::PartyRoleKind.create!(key: :division, title: 'Division') Parties::PartyRoleKind.create!(key: :internal_organization, title: 'Internal Organization') Parties::PartyRoleKind.create!(key: :other_organization_unit, title: 'Other Organization Unit') Parties::PartyRoleKind.create!(key: :employer, title: 'Employer') # Site Owner is super user across system -- only assign to one organization Parties::PartyRoleKind.create!(key: :site_owner, title: 'Site Owner') # Corporate Entity Kinds Parties::PartyRoleKind.create!(key: :s_corporation, title: 'S Corporation') Parties::PartyRoleKind.create!(key: :c_corporation, title: 'C Corporation') Parties::PartyRoleKind.create!(key: :limited_liability_corporation, title: 'Limited Liability Corporation') Parties::PartyRoleKind.create!(key: :limited_liability_partnership, title: 'Limited Liability Partnership') Parties::PartyRoleKind.create!(key: :non_profit_501c3, title: 'Non Profit 501c(3) Corporation') Parties::PartyRoleKind.create!(key: :other_non_profit, title: 'Other Non Profit') Parties::PartyRoleKind.create!(key: :household_employer, title: 'Household Employer') Parties::PartyRoleKind.create!(key: :regulatory_agency, title: 'Regulatory Agency') # UITS/PFL Parties::PartyRoleKind.create!(key: :tpa, title: 'Third Party Administrator') Parties::PartyRoleKind.create!(key: :tpa_agent, title: 'TPA Agent') Parties::PartyRoleKind.create!(key: :uits_liable, title: 'Unemployment Insurance Tax Liable') Parties::PartyRoleKind.create!(key: :uits_exempt, title: 'Unemployment Insurance Tax Exempt') Parties::PartyRoleKind.create!(key: :uits_contributing, title: 'UI Tax Contribution Payment Model') Parties::PartyRoleKind.create!(key: :uits_reimbursing, title: 'UI Tax Reimbursement Payment Model') Parties::PartyRoleKind.create!(key: :uits_qtr_filer, title: 'UI Tax Quarterly Filer') Parties::PartyRoleKind.create!(key: :uits_annual_filer, title: 'UI Tax Annual Filer') Parties::PartyRoleKind.create!(key: :pfl_liable, title: 'Paid Family Leave Tax Liable') Parties::PartyRoleKind.create!(key: :pfl_exempt, title: 'Paid Family Leave Tax Exempt') Parties::PartyRoleKind.create!(key: :pfl_opt_in, title: 'Paid Family Leave Tax Opted-In') puts "*"*80 puts "Populating Relationships" puts "*"*80 Parties::PartyRelationshipKind.create!( key: :employment, title: 'Employment', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :employee), Parties::PartyRoleKind.find_by(key: :employer), ] ) Parties::PartyRelationshipKind.create!( key: :organization_officer, title: 'Organization Officer', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :parent_organization), Parties::PartyRoleKind.find_by(key: :owner_or_officer), ] ) Parties::PartyRelationshipKind.create!( key: :organization_ui_primary_contact, title: 'Organization UI Primary Contact', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :contact), Parties::PartyRoleKind.find_by(key: :parent_organization), ] ) Parties::PartyRelationshipKind.create!( key: :organization_ui_secondary_contact, title: 'Organization UI Secondary Contact', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :contact), Parties::PartyRoleKind.find_by(key: :parent_organization), ] ) Parties::PartyRelationshipKind.create!( key: :organization_pfl_primary_contact, title: 'Organization PFL Primary Contact', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :contact), Parties::PartyRoleKind.find_by(key: :parent_organization), ] ) Parties::PartyRelationshipKind.create!( key: :organization_pfl_secondary_contact, title: 'Organization PFL Secondary Contact', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :contact), Parties::PartyRoleKind.find_by(key: :parent_organization), ] ) Parties::PartyRelationshipKind.create!( key: :ui_tpa_relationship, title: 'UI TPA Relationship', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :tpa), Parties::PartyRoleKind.find_by(key: :employer), ] ) Parties::PartyRelationshipKind.create!( key: :pfl_tpa_relationship, title: 'PFL TPA Relationship', party_role_kinds: [ Parties::PartyRoleKind.find_by(key: :tpa), Parties::PartyRoleKind.find_by(key: :employer), ] )
ipublic/marketplace
spec/factories/integrations_get_backruptcy_notices.rb
<reponame>ipublic/marketplace<gh_stars>0 FactoryBot.define do factory :integrations_get_backruptcy_notice, class: 'Integrations::GetBackruptcyNotice' do end end
ipublic/marketplace
spec/factories/integrations_register_tpas.rb
FactoryBot.define do factory :integrations_register_tpa, class: 'Integrations::RegisterTpa' do end end
ipublic/marketplace
spec/factories/products_individual_dental_insurances.rb
FactoryBot.define do factory :products_individual_dental_insurance, class: 'Products::IndividualDentalInsurance' do end end
ipublic/marketplace
spec/factories/dispatcher_activities_group_renew_activities.rb
<gh_stars>0 FactoryBot.define do factory :dispatcher_activities_group_renew_activity, class: 'Dispatcher::Activities::GroupRenewActivity' do end end
ipublic/marketplace
spec/factories/documents.rb
FactoryBot.define do factory :document do end end