Associated Function Resources

As explained in the Core Resource Model docs, methods like rate and cron simply perform some wrapper logic and then ultimately call the resource method. We’ll cover that wrapper logic and expansion process in more details here.

The rate method creates a CloudWatch Event Rule resource. This Event Rule resource is associated with the dig Lambda function. Here’s the example again:

class HardJob < ApplicationJob
  rate "10 hours" # every 10 hours
  def dig
    puts "done digging"
  end
end

What happens is that Jets takes the rate method, performs some wrapper logic, and calls the core resource method in the first pass. The code looks something like this after the first pass:

class HardJob < ApplicationJob
  resource(
    "{namespace}EventsRule": {
      Type: "AWS::Events::Rule",
      Properties: {
        ScheduleExpression: "rate(10 hours)",
        State: "ENABLED",
        Targets: [{
          Arn: "!GetAtt {namespace}LambdaFunction.Arn",
          Id: "{namespace}RuleTarget"
        }]
      }
    }
  )
  def dig
    puts "done digging"
  end
end

In the second pass, Jets replaces the {namespace} with an identifier a value that has method name that represents the Lambda function. For example:

Before After
{namespace} HardJobDig

The final code looks something like this:

class HardJob < ApplicationJob
  resource(
    HardJobDigEventsRule: {
      Type: "AWS::Events::Rule",
      Properties: {
        ScheduleExpression: "rate(10 hours)",
        State: "ENABLED",
        Targets: [{
          Arn: "!GetAtt HardJobDigLambdaFunction.Arn",
          Id: "HardJobDigRuleTarget"
        }]
      }
    }
  )
  def dig
    puts "done digging"
  end
end

The resource method creates the AWS::Events::Rule as a CloudFormation resource. The keys of the Hash structure use the underscore format following Ruby naming convention. As part of CloudFormation template processing, the underscored keys are camelized.

Understanding the core resource model is key to unlocking the power of full customization to a Jets application. Once you get used to the resource method, you could start defining your own custom convenience resource methods that wrap the resource method for more concise code as Associated Resources Extensions.

Note: Users who have used Jets for a while, IE, jets v3 and below, may notice that the CloudFormation keys are CamelCase not underscore. Both underscore and CamelCase works. Jets runs a custom Camelizer to properly transform the keys regardless of the format. You can use either format. Have found that once we get near CloudFormation land, it’s easier to think on CloudFormation terms. Feel that resource at the crossing of that mental boundary. More thoughts: CloudFomation CamelCase vs Ruby Underscore Thoughts.