# encoding: utf-8 module FeduxOrgStdlib module Roles # Typable # # If need to determine the file type of a object, you can include # `FeduxOrgStdlib::Roles::Typeable`. You only need to define a method # `source_path`, which is used by the included methods. It needs to return # a `Pathname`. # # @example # # class MyClass # include FeduxOrgStdlib::Roles::Typeable # # private # # attr_reader :source_path # # public # # def initialize(source_path:) # @source_path = Pathname.new(source_path) # end # end # # object = MyClass.new('images/image.png') # object.type # => :image # # object = MyClass.new('images/image.css') # object.type # => :stylesheet # object.image? # => false # object.stylesheet? # => true module Typable def source_path fail NoMethodError, :source_path end # Check on file type # # @return [true, false] # Is true if has type def type?(t) type == t end # Determine type of object def type @type ||= if image? :image elsif script? :script elsif stylesheet? :stylesheet elsif font? :font else :unknown end end # Is file? def file? source_path.file? end # Is it a valid # @return [true, false] # If it is valid return true def valid? file? end # Has file extensions # # @param [Array] exts # The extensions to check def extnames?(*exts) !(extnames & exts.flatten).empty? end # Return extensions def extnames source_path.basename.to_s.scan(/(\.[^.]+)/).flatten end # Is image? def image? image_by_path? || (image_by_extension? && !font_by_path?) end private # Is image by path? def image_by_path? source_path.dirname.basename.to_s == 'images' || source_path.dirname.basename.to_s == 'img' end # Is image by extension? def image_by_extension? extnames?(*%w(.gif .png .jpg .jpeg .webp .svg .svgz)) end public # Is stylesheet? def stylesheet? stylesheet_by_path? || stylesheet_by_extension? end private # Is stylesheet by extension? def stylesheet_by_extension? extnames?(*%w(.css .sass .scss .styl .less)) end # Is stylesheet by path? def stylesheet_by_path? source_path.dirname.basename.to_s == 'stylesheets' || source_path.dirname.basename.to_s == 'css' end public # Is font? def font? font_by_path? || font_by_extension? end private # Is font by path? def font_by_path? source_path.dirname.basename.to_s == 'fonts' end # Is font by extension? def font_by_extension? extnames?(*%w(.ttf .woff .eot .otf .svg .svgz)) end public # Is script? def script? script_by_path? || script_by_extension? end private # Is script by path? def script_by_path? source_path.dirname.basename.to_s == 'javascripts' || source_path.dirname.basename.to_s == 'js' end # Is script by extension? def script_by_extension? extnames?(*%w(.js .coffee)) end end end end